Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Dealing with contents when resizing a canvas</strong></p> <p>If you resize the canvas, the drawn content is always erased. That's how canvas behaves. </p> <p>You can either redraw the content after resizing or you can save the content as image data and restore after resizing (see canvas.toDataURL). </p> <p>Here is code and a Fiddle: <a href="http://jsfiddle.net/m1erickson/V6SVz/" rel="noreferrer">http://jsfiddle.net/m1erickson/V6SVz/</a></p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /&gt; &lt;!-- reset css --&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery.min.js"&gt;&lt;/script&gt; &lt;style&gt; body{ background-color: ivory; padding:10px; } canvas{border:1px solid red;} &lt;/style&gt; &lt;script&gt; $(function(){ var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); // draw some content ctx.lineWidth=3; ctx.fillStyle="blue"; ctx.strokeStyle="red"; ctx.rect(50,50,100,50); ctx.fill(); ctx.stroke(); ctx.font="14px Verdana"; ctx.fillStyle="white"; ctx.fillText("Scale Me",65,75); function saveResizeAndRedisplay(scaleFactor){ // save the canvas content as imageURL var data=canvas.toDataURL(); // resize the canvas canvas.width*=scaleFactor; canvas.height*=scaleFactor; // scale and redraw the canvas content var img=new Image(); img.onload=function(){ ctx.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height); } img.src=data; } $("#resizer").click(function(){ saveResizeAndRedisplay(1.5); }); }); // end $(function(){}); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;button id="resizer"&gt;Click to resize the canvas&lt;/button&gt;&lt;br/&gt; &lt;canvas id="canvas" width=200 height=150&gt;&lt;/canvas&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload