{"id":789,"date":"2020-10-03T20:46:29","date_gmt":"2020-10-03T20:46:29","guid":{"rendered":"https:\/\/potatodie.nl\/diffuse-write-ups\/?p=789"},"modified":"2021-10-03T08:17:58","modified_gmt":"2021-10-03T08:17:58","slug":"creating-a-magnifying-glass-with-html5-canvas","status":"publish","type":"post","link":"https:\/\/potatodie.nl\/diffuse-write-ups\/creating-a-magnifying-glass-with-html5-canvas\/","title":{"rendered":"Creating a magnifying glass with html5 canvas"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">It is surprisingly easy to manipulate images in the browser using the html5 element <code>canvas<\/code>. For instance, we can cut out part of the image and paste it back at another positon, in the mean time changing the shape or color of it. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">And it doesn&#8217;t have to be rectangles only! Let&#8217;s create an example where we take a circular area of a downscaled image, then paste it back magnified. In effect a hand-lens or magnifying glass. A usefull tool!<\/p>\n\n\n\n<p class=\"codepen\" data-height=\"407\" data-theme-id=\"dark\" data-default-tab=\"result\" data-user=\"potatoDie\" data-slug-hash=\"vYGogKQ\" style=\"height: 407px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;\" data-pen-title=\"Magnifying Glass\">\n  <span>See the Pen <a href=\"https:\/\/codepen.io\/potatoDie\/pen\/vYGogKQ\">\n  Magnifying Glass<\/a> by potatoDie (<a href=\"https:\/\/codepen.io\/potatoDie\">@potatoDie<\/a>)\n  on <a href=\"https:\/\/codepen.io\">CodePen<\/a>.<\/span>\n<\/p>\n<script async=\"\" src=\"https:\/\/static.codepen.io\/assets\/embed\/ei.js\"><\/script>\n\n\n\n<p class=\"wp-block-paragraph\">In the Codepen above you see the original image on the left. An intermediate canvas containing a fragment of the image in the middle. And on the right the canvas containing a copy of the original image with the pasted artwork. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s see how it&#8217;s done.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The original and its copy<\/h2>\n\n\n<div class=\"wp-block-advanced-gutenberg-blocks-code\">\n  <header class=\"wp-block-advanced-gutenberg-blocks-code__header\">\n    <div class=\"wp-block-advanced-gutenberg-blocks-code__lang is-lang-js\">\n      JS    <\/div>\n    <div class=\"wp-block-advanced-gutenberg-blocks-code__file\">\n          <\/div>\n  <\/header>\n  <textarea \n    class=\"wp-block-advanced-gutenberg-blocks-code__source\" \n    name=\"codemirror-1378194602\" \n    id=\"codemirror-1378194602\"\n  >let image = document.getElementById(&quot;original&quot;)\nlet w = image.naturalWidth\nlet h = image.naturalHeight<\/textarea>\n  <script>\n    CodeMirror.fromTextArea( document.getElementById('codemirror-1378194602'), {\n      mode: 'javascript',\n      readOnly: true,\n      theme: 'hopscotch', \n      lineNumbers: true,\n      firstLineNumber: 1,\n      matchBrackets: true,\n      indentUnit: 4,\n      tabSize: 4,\n      lineWrapping: true,\n    } ); \n  <\/script>\n<\/div>\n\n\n\n<p class=\"wp-block-paragraph\">First we get a reference to the original image, and we store its dimensions. Note that the image is downscaled and we store the actual width and height of the image, not the width and height as it is shown on the page. This image of hazel is 1,400px \u00d7 2,277px, so there is plenty of room for magnification.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now copy the image to the canvas, using <code>drawImage<\/code>.<\/p>\n\n\n<div class=\"wp-block-advanced-gutenberg-blocks-code\">\n  <header class=\"wp-block-advanced-gutenberg-blocks-code__header\">\n    <div class=\"wp-block-advanced-gutenberg-blocks-code__lang is-lang-js\">\n      JS    <\/div>\n    <div class=\"wp-block-advanced-gutenberg-blocks-code__file\">\n          <\/div>\n  <\/header>\n  <textarea \n    class=\"wp-block-advanced-gutenberg-blocks-code__source\" \n    name=\"codemirror-1842161624\" \n    id=\"codemirror-1842161624\"\n  >let canvas = document.getElementById(&quot;hCanvas&quot;)\ncanvas.width = w\ncanvas.height = h\n\nlet ctx = canvas.getContext(&#039;2d&#039;)\n\nctx.drawImage(image, 0, 0)<\/textarea>\n  <script>\n    CodeMirror.fromTextArea( document.getElementById('codemirror-1842161624'), {\n      mode: 'javascript',\n      readOnly: true,\n      theme: 'hopscotch', \n      lineNumbers: false,\n      firstLineNumber: 1,\n      matchBrackets: true,\n      indentUnit: 4,\n      tabSize: 4,\n      lineWrapping: true,\n    } ); \n  <\/script>\n<\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Properties of magnification<\/h2>\n\n\n<div class=\"wp-block-advanced-gutenberg-blocks-code\">\n  <header class=\"wp-block-advanced-gutenberg-blocks-code__header\">\n    <div class=\"wp-block-advanced-gutenberg-blocks-code__lang is-lang-js\">\n      JS    <\/div>\n    <div class=\"wp-block-advanced-gutenberg-blocks-code__file\">\n          <\/div>\n  <\/header>\n  <textarea \n    class=\"wp-block-advanced-gutenberg-blocks-code__source\" \n    name=\"codemirror-239799988\" \n    id=\"codemirror-239799988\"\n  >let size = w \/ 4 \/\/ Size (radius) of magnifying glass\nlet magnification = 2\nlet r = size \/ magnification \/\/ Radius of part we want to magnify\n\nlet px = w \/ 3.5\nlet py = h \/ 4<\/textarea>\n  <script>\n    CodeMirror.fromTextArea( document.getElementById('codemirror-239799988'), {\n      mode: 'javascript',\n      readOnly: true,\n      theme: 'hopscotch', \n      lineNumbers: false,\n      firstLineNumber: 5,\n      matchBrackets: true,\n      indentUnit: 4,\n      tabSize: 4,\n      lineWrapping: true,\n    } ); \n  <\/script>\n<\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Define the size of the loupe, the magnification factor and calculate the radius needed of the fragment of the original so that magnified it fills the whole magnifying glass.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We also position the (center of) the loupe. Here <code>px<\/code> and <code>py<\/code> are hard coded somewhat arbitrarily. Wouldn&#8217;t it be nice if a user could determine the position of the loupe? We&#8217;ll come to that in <a href=\"https:\/\/potatodie.nl\/diffuse-write-ups\/magnify-an-image-with-a-draggable-loupe\/\" data-type=\"post\" data-id=\"815\">this post<\/a>!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Create a pattern<\/h2>\n\n\n<div class=\"wp-block-advanced-gutenberg-blocks-code\">\n  <header class=\"wp-block-advanced-gutenberg-blocks-code__header\">\n    <div class=\"wp-block-advanced-gutenberg-blocks-code__lang is-lang-js\">\n      JS    <\/div>\n    <div class=\"wp-block-advanced-gutenberg-blocks-code__file\">\n          <\/div>\n  <\/header>\n  <textarea \n    class=\"wp-block-advanced-gutenberg-blocks-code__source\" \n    name=\"codemirror-1942534247\" \n    id=\"codemirror-1942534247\"\n  >let tileCanvas = document.getElementById(&quot;tCanvas&quot;)\ntileCanvas.width = 2 * size\ntileCanvas.height = 2 * size\n\ntileCanvas.getContext(&#039;2d&#039;).drawImage(canvas, px - r, py - r, 2 * r, 2 * r, 0, 0, 2 * size, 2 * size)\n\nlet pattern = ctx.createPattern(tileCanvas, &quot;repeat&quot;)\n\nctx.fillStyle = pattern<\/textarea>\n  <script>\n    CodeMirror.fromTextArea( document.getElementById('codemirror-1942534247'), {\n      mode: 'javascript',\n      readOnly: true,\n      theme: 'hopscotch', \n      lineNumbers: false,\n      firstLineNumber: 1,\n      matchBrackets: true,\n      indentUnit: 4,\n      tabSize: 4,\n      lineWrapping: true,\n    } ); \n  <\/script>\n<\/div>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;re copying part of the canvas that contains the image copy to a second, smaller, canvas. Again we&#8217;re using <code>drawImage<\/code>, but now with nine arguments. Apart from the source canvas image it instructs the <code>drawImage <\/code>function which source rectangle to render on what destination rectangle. See the MDN Web Docs for the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/CanvasRenderingContext2D\/drawImage\">possible parameters.<\/a><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Next a pattern is created based on this intermediate canvas, and the pattern will be used for <code>fill<\/code> on the main canvas.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Positioning the pattern<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">If we now fill a shape, the position of the pattern is determined by the coordinate system. It starts at the origin, so if we want the pattern to start at a specific point (as we do) we should transform the rendering context to set the new origin.<\/p>\n\n\n<div class=\"wp-block-advanced-gutenberg-blocks-code\">\n  <header class=\"wp-block-advanced-gutenberg-blocks-code__header\">\n    <div class=\"wp-block-advanced-gutenberg-blocks-code__lang is-lang-js\">\n      JS    <\/div>\n    <div class=\"wp-block-advanced-gutenberg-blocks-code__file\">\n          <\/div>\n  <\/header>\n  <textarea \n    class=\"wp-block-advanced-gutenberg-blocks-code__source\" \n    name=\"codemirror-1492578679\" \n    id=\"codemirror-1492578679\"\n  >ctx.translate(px - size, py - size)<\/textarea>\n  <script>\n    CodeMirror.fromTextArea( document.getElementById('codemirror-1492578679'), {\n      mode: 'javascript',\n      readOnly: true,\n      theme: 'hopscotch', \n      lineNumbers: false,\n      firstLineNumber: 1,\n      matchBrackets: true,\n      indentUnit: 4,\n      tabSize: 4,\n      lineWrapping: true,\n    } ); \n  <\/script>\n<\/div>\n\n\n\n<p class=\"wp-block-paragraph\">This moves the origin of the context to the left top of the (rectangular) area we want to draw our filled circle in. Relative to the new origin, the center of the circle is <code>(size, size)<\/code>. The third parameter of <code>arc <\/code>below determines the radius of the circle and is also <code>size<\/code>.<\/p>\n\n\n<div class=\"wp-block-advanced-gutenberg-blocks-code\">\n  <header class=\"wp-block-advanced-gutenberg-blocks-code__header\">\n    <div class=\"wp-block-advanced-gutenberg-blocks-code__lang is-lang-js\">\n      JS    <\/div>\n    <div class=\"wp-block-advanced-gutenberg-blocks-code__file\">\n          <\/div>\n  <\/header>\n  <textarea \n    class=\"wp-block-advanced-gutenberg-blocks-code__source\" \n    name=\"codemirror-969758974\" \n    id=\"codemirror-969758974\"\n  >ctx.beginPath()\nctx.arc(size, size, size, 0, 2 * Math.PI)\nctx.fill()\nctx.strokeStyle = &quot;orangered&quot;\nctx.lineWidth = 12\nctx.stroke()<\/textarea>\n  <script>\n    CodeMirror.fromTextArea( document.getElementById('codemirror-969758974'), {\n      mode: 'javascript',\n      readOnly: true,\n      theme: 'hopscotch', \n      lineNumbers: false,\n      firstLineNumber: 1,\n      matchBrackets: true,\n      indentUnit: 4,\n      tabSize: 4,\n      lineWrapping: true,\n    } ); \n  <\/script>\n<\/div>\n\n\n\n<p class=\"wp-block-paragraph\">And that&#8217;s it!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Alternative with clipping<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">I suppose you could reach the same result without the intermediate canvas and a pattern. <code>drawImage <\/code>is quite a flexible tool and you can draw (part of) a canvas on itself.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Also, we can exclude parts of the canvas from being drawn on by using <code>clip<\/code>, to fill a circular shape rather than a rectangle. It might we worth trying that out! Use <a href=\"https:\/\/codepen.io\/potatoDie\/pen\/vYGogKQ\">this pen<\/a> (shown above) as a starting point.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Actually, the <a href=\"https:\/\/potatodie.nl\/diffuse-write-ups\/magnify-an-image-with-a-draggable-loupe\/\" data-type=\"post\" data-id=\"815\">follow-up post<\/a> does use clipping to draw circular shapes, instead of a pattern.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>It is surprisingly easy to manipulate images in the browser using the html5 element canvas. For instance, we can cut out part of the image and paste it back at another positon, in the mean time changing the shape or color of it. And it doesn&#8217;t have to be rectangles only!<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[50,20,7],"tags":[39,44,41,40],"class_list":["post-789","post","type-post","status-publish","format-standard","hentry","category-graphics","category-javascript","category-web-development","tag-canvas","tag-clip","tag-hazel","tag-pattern"],"acf":[],"_links":{"self":[{"href":"https:\/\/potatodie.nl\/diffuse-write-ups\/wp-json\/wp\/v2\/posts\/789","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/potatodie.nl\/diffuse-write-ups\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/potatodie.nl\/diffuse-write-ups\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/potatodie.nl\/diffuse-write-ups\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/potatodie.nl\/diffuse-write-ups\/wp-json\/wp\/v2\/comments?post=789"}],"version-history":[{"count":8,"href":"https:\/\/potatodie.nl\/diffuse-write-ups\/wp-json\/wp\/v2\/posts\/789\/revisions"}],"predecessor-version":[{"id":826,"href":"https:\/\/potatodie.nl\/diffuse-write-ups\/wp-json\/wp\/v2\/posts\/789\/revisions\/826"}],"wp:attachment":[{"href":"https:\/\/potatodie.nl\/diffuse-write-ups\/wp-json\/wp\/v2\/media?parent=789"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/potatodie.nl\/diffuse-write-ups\/wp-json\/wp\/v2\/categories?post=789"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/potatodie.nl\/diffuse-write-ups\/wp-json\/wp\/v2\/tags?post=789"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}