javascript 调整大小时 html5 画布重绘

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30217380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:54:16  来源:igfitidea点击:

html5 canvas redraw on resize

javascriptjqueryhtmlcanvasredraw

提问by CodeGust

I have two canvas elements and need them to be resized on buttons click.

我有两个画布元素,需要在单击按钮时调整它们的大小。

<div class="sDetails"><div>
                        <div id="canvasDiv" style="width: 310px;"><canvas id="canvasGraph"></canvas></div></div>
<div class="kDetails"><div><div>
<div id="canvasDiv" style="width: 310px; height: 240px;"><canvas id="canvasGraph"></canvas></div></div>

and the script:

和脚本:

   var sketch;var sketch_sl;var onPaint;var canvas=null;var ctx=null;var tmp_ctx=null;
    function drawCanvas(div) {
        canvas = document.querySelector(div + " #canvasGraph");
        ctx = canvas.getContext('2d');
        sketch = document.querySelector(div + " #canvasDiv");
        sketch_sl = getComputedStyle(sketch);
        canvas.width = parseInt(sketch_style.getPropertyValue('width'));
        canvas.height = parseInt(sketch_style.getPropertyValue('height'));
        tmp_canvas = document.createElement('canvas');
        tmp_ctx = tmp_canvas.getContext('2d');
        tmp_canvas.id = 'tmp_canvas';
        tmp_canvas.width = canvas.width;
        tmp_canvas.height = canvas.height;
        sketch.appendChild(tmp_canvas);

the redraw function:

重绘功能:

// here I must redraw my lines resized 2 times ( *cScale ) where cScale=2 or =1
function drawScales(ctx, canvas) 
        ctx.strokeStyle = 'green';
        ctx.fillStyle = 'green';
        ctx.beginPath();
        ctx.moveTo(5, 0);
        ctx.lineTo(0, canvas.height);
        scaleStep = 24*cScale;

for some reason it works really bad, old positions stay. Is there a way to completely delete the whole canvas and append it or redraw it completely?

出于某种原因,它的效果非常糟糕,旧职位仍然存在。有没有办法完全删除整个画布并附加它或完全重绘它?

I tried canvas.width=canvas.width, tried ctx.clearRect(0, 0, canvas.width, canvas.height);tmp_ctx.clearRect(0, 0, canvas.width, canvas.height);, tried $(".sDetails #canvasGraph")[0].reset();

我试过canvas.width=canvas.width,试过ctx.clearRect(0, 0, canvas.width, canvas.height);tmp_ctx.clearRect(0, 0, canvas.width, canvas.height);,试过$(".sDetails #canvasGraph")[0].reset();

logically, drawCanvas(".sDetails");drawLines(ctx, canvas);should redraw it from scratch but it will not.

从逻辑上讲,drawCanvas(".sDetails");drawLines(ctx, canvas);应该从头开始重新绘制它,但不会。

采纳答案by CodeGust

I decided to use a scale variable to resize my scales. I resize the canvas canvas.width *= 2;and then I redraw my scales.

我决定使用比例变量来调整比例。我调整画布的大小canvas.width *= 2;,然后重新绘制我的比例。

var scaleStep;

var scaleStep;

and use add it into the code: ctx.lineTo(12*24*cScale+12, canvas.height-24);where the scaling needs to be done. The scaleStep is 2 when maximizing the canvas and 1 when returning to the original size.

并使用将其添加到代码中:ctx.lineTo(12*24*cScale+12, canvas.height-24);需要进行缩放的地方。最大化画布时 scaleStep 为 2,返回原始大小时为 1。

回答by markE

Resize the canvas element's width& heightand use context.scaleto redraw the original drawings at their newly scaled size.

调整画布元素的width&大小height并用于context.scale以新缩放的大小重新绘制原始绘图。

  • Resizing the canvas element will automatically clear all drawings off the canvas.

  • Resizing will also automatically reset all context properties back to their default values.

  • Using context.scaleis useful because then the canvas will automatically rescale the original drawings to fit on the newly sized canvas.

  • Important: Canvas will not automatically redraw the original drawings...you must re-issue the original drawing commands.

  • 调整画布元素的大小将自动清除画布上的所有绘图。

  • 调整大小还会自动将所有上下文属性重置为其默认值。

  • 使用context.scale很有用,因为这样画布会自动重新缩放原始绘图以适应新大小的画布。

  • 重要提示:Canvas 不会自动重绘原始绘图...您必须重新发出原始绘图命令。

Illustration with 2 canvases at same size (their sizes are controlled by range controls)

带有 2 个大小相同的画布的插图(它们的大小由范围控件控制)

enter image description here

在此处输入图片说明

Illustration with left canvas resized larger

将左侧画布放大的插图

enter image description here

在此处输入图片说明

Illustration with right canvas resized larger

将右侧画布放大的插图

enter image description here

在此处输入图片说明

Here's example code and a Demo. This demo uses range elements to control the resizing, but you can also do the resizing+redrawing inside window.onresize

这是示例代码和演示。这个demo使用range元素来控制resize,但是你也可以在里面做resize+redrawingwindow.onresize

var canvas1=document.getElementById("canvas1");
var ctx1=canvas1.getContext("2d");
var canvas2=document.getElementById("canvas2");
var ctx2=canvas2.getContext("2d");
var originalWidth=canvas1.width;
var originalHeight=canvas1.height;

var scale1=1;
var scale2=1;

$myslider1=$('#myslider1');
$myslider1.attr({min:50,max:200}).val(100);
$myslider1.on('input change',function(){
  var scale=parseInt($(this).val())/100;
  scale1=scale;
  redraw(ctx1,scale);
});
$myslider2=$('#myslider2');
$myslider2.attr({min:50,max:200}).val(100);
$myslider2.on('input change',function(){
  var scale=parseInt($(this).val())/100;
  scale2=scale;
  redraw(ctx2,scale);
});

draw(ctx1);
draw(ctx2);

function redraw(ctx,scale){

  // Resizing the canvas will clear all drawings off the canvas
  // Resizing will also automatically clear the context
  // of all its current values and set default context values
  ctx.canvas.width=originalWidth*scale;
  ctx.canvas.height=originalHeight*scale;

  // context.scale will scale the original drawings to fit on
  // the newly resized canvas
  ctx.scale(scale,scale);

  draw(ctx);

  // always clean up! Reverse the scale
  ctx.scale(-scale,-scale);

}

function draw(ctx){
  // note: context.scale causes canvas to do all the rescaling
  //       math for us, so we can always just draw using the 
  //       original sizes and x,y coordinates
  ctx.beginPath();
  ctx.moveTo(150,50);
  ctx.lineTo(250,150);
  ctx.lineTo(50,150);
  ctx.closePath();
  ctx.stroke();
  ctx.fillStyle='skyblue';
  ctx.beginPath();
  ctx.arc(150,50,20,0,Math.PI*2);
  ctx.closePath();
  ctx.fill();
  ctx.stroke();
  ctx.beginPath();
  ctx.arc(250,150,20,0,Math.PI*2);
  ctx.closePath();
  ctx.fill();
  ctx.stroke();
  ctx.beginPath();;
  ctx.arc(50,150,20,0,Math.PI*2);
  ctx.fill();
  ctx.stroke();
}

$("#canvas1, #canvas2").mousemove(function(e){handleMouseMove(e);});
var $mouse=$('#mouse');

function handleMouseMove(e){

  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();


  var bb=e.target.getBoundingClientRect();
  mouseX=parseInt(e.clientX-bb.left);
  mouseY=parseInt(e.clientY-bb.top);

  if(e.target.id=='canvas1'){
    $mouse.text('Mouse1: '+mouseX/scale1+' / '+mouseY/scale1+' (scale:'+scale1+')');
  }else{
    $mouse.text('Mouse2: '+mouseX/scale2+' / '+mouseY/scale2+' (scale:'+scale2+')');
  }

}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>Resize left canvas</div>
<input id=myslider1 type=range><br>
<div>Resize right canvas</div>
<input id=myslider2 type=range><br>
<h4 id=mouse>Mouse coordinates:</h4>
<canvas id="canvas1" width=300 height=300></canvas>
<canvas id="canvas2" width=300 height=300></canvas>

回答by CodeGust

If you need scale-independent positions you could use normalized values ([0, 1]) instead and use the size of canvas as the scale factor. This way you can scale and store values without too much concern about the actual target size.

如果您需要与比例无关的位置,您可以使用归一化值 ([0, 1]) 代替,并使用画布的大小作为比例因子。通过这种方式,您可以缩放和存储值,而无需过多关注实际目标大小。

You would also be able to use the mouse positions almost as is and normalize by just dividing them on canvas size.

您还可以几乎按原样使用鼠标位置,并通过将它们按画布大小划分来进行标准化。

For example:

例如:

When rendering, a point of (1,1) will always draw in lower-right corner as you would do (1 * canvas.width, 1 * canvas.height).

渲染,点(1,1)总是在画的右下角,你会怎么做(1 * canvas.width, 1 * canvas.height)

When you storea point you would use the mouse position and divide it on the canvas dimension, for example, if I click in the lower right corner of a canvas of size 400x200, the points would be 400/400 = 1, 200/200 = 1.

当您存储一个点时,您将使用鼠标位置并将其划分在画布尺寸上,例如,如果我单击大小为 400x200 的画布的右下角,则点将是 400/400 = 1, 200/200 = 1。

Note that width and height would be exclusive (ie. width-1 etc.), but for sake of simplicity...

请注意,宽度和高度将是互斥的(即宽度 1 等),但为了简单起见......

Example

例子

In this example you can start with any size of the canvas, draw points which are normalized, change size of canvas and have the points redrawn proportionally relative to the original position.

在此示例中,您可以从任意大小的画布开始,绘制标准化的点,更改画布的大小并相对于原始位置按比例重绘点。

var rng = document.querySelector("input"),
    c = document.querySelector("canvas"),
    ctx = c.getContext("2d"),
    points = [];

// change canvas size and redraw all points
rng.onchange = function() {
  c.width = +this.value;
  render();
};

// add a new normalized point to array
c.onclick = function(e) {
  var r = this.getBoundingClientRect(),   // to adjust mouse position
      x = e.clientX - r.left,
      y = e.clientY - r.top;
  points.push({
    x: x / c.width,                       // normalize value to range [0, 1]
    y: y / c.height
  });                                     // store point
  render();                               // redraw (for demo)
};

function render() {
  ctx.clearRect(0, 0, c.width, c.height); // clear canvas
  ctx.beginPath();                        // clear path
  for(var i = 0, p; p = points[i]; i++) { // draw points as fixed-size circles
    var x = p.x * c.width,                // normalized to absolute values
        y = p.y * c.height;
    
    ctx.moveTo(x + 5, y);
    ctx.arc(x, y, 5, 0, 6.28);
    ctx.closePath();
  }
  ctx.stroke();
}
canvas {background:#ddd}
<h3>Click on canvas to add points, then resize</h3>
<label>Width: <input type="range" min=50 max=600 value=300></label><br>
<canvas></canvas>