【问题标题】:HTML 5 Canvas. How to rotate (keep rotating) only one object (of >1)?HTML 5 画布。如何仅旋转(保持旋转)一个对象(> 1)?
【发布时间】:2017-01-20 21:54:58
【问题描述】:

我正在尝试在画布中旋转,但我还没有找到我的问题的答案。

一个正方形要保持静止。在指定点旋转的另一个正方形。我可以让整个画布在那时旋转,或者根本不旋转。但是我不能让一个正方形是静态的,而一个是旋转的。

请在此处查看我的 codepen 演示:http://codepen.io/richardk70/pen/EZWMXx

javascript:

HEIGHT = 400;
WIDTH = 400;

function draw(){

var ctx = document.getElementById("canvas").getContext('2d');
ctx.clearRect(0,0,WIDTH,HEIGHT);

// draw black square
ctx.save();
ctx.fillStyle = "black";
ctx.beginPath();  
ctx.fillRect(75,75,100,100);
ctx.closePath();
ctx.restore();

// attempt to rotate small, maroon square only
ctx.save();
ctx.translate(225,225);

// small maroon square
ctx.fillStyle = "maroon";
ctx.beginPath();
ctx.fillRect(-25,-25,50,50);
ctx.closePath();
ctx.rotate(.1);
ctx.translate(-225,-225);

// comment out below line to spin
// ctx.restore();

window.requestAnimationFrame(draw);
}

window.requestAnimationFrame(draw);

我知道我可以制作分层画布,但肯定可以只在一个画布层中完成吗?本教程中的时钟 (https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations) 不正是这样做的吗?

感谢您的任何帮助。

【问题讨论】:

  • 如果您查看链接的示例,它会根据当前时间调整旋转量,因此每次绘制调用都会稍微移动行星。您正在尝试在上下文中累积旋转,但这不是它的工作方式。

标签: javascript html5-canvas


【解决方案1】:

要仅旋转一张图像或渲染,您需要将画布变换状态恢复为默认值。

此功能将渲染您的对象旋转缩放和平移,但不影响任何其他渲染。

顺便说一句,您不需要使用 beginPath 是渲染调用以填充或描边开头,例如ctx.fillRectctx.strokeRectctx.fillTextctx.strokeText,如果需要,您只需使用ctx.closePathctx.beginPath 调用后创建一条从最后一个路径点到上一个ctx.moveTo 点或第一个路径点的线

您也不需要为所有渲染使用保存和恢复。只有在需要恢复之前的画布状态时才使用它。

ctx = canvas.getContext("2d");

function drawBox(col,size,x,y,scale,rot){
    ctx.fillStyle = col;
    // use setTransform as it overwrites the canvas transform rather than multiply it as the other transform functions do
    ctx.setTransform(scale, 0, 0, scale, x, y);
    ctx.rotate(rot);
    ctx.fillRect(-size / 2,-size / 2, size, size);  
}


function update(time){
    ctx.clearRect(0,0,512,256)
    drawBox("black",100,125,125,1,0); // draw none rotated box
    drawBox("maroon",50,225,125,1,time / 500); // draw rotating box
    drawBox("green",25,275,100,1,-time / 250); // draw rotating box
    drawBox("green",25,275,150,1,-time / 250); // draw rotating box
    // after using transforms you need to reset the transform to the default
    // if you plan to render anything in the default coordinate system
    ctx.setTransform(1, 0 ,0 , 1, 0, 0); // reset to default transform

    requestAnimationFrame(update);
}

requestAnimationFrame(update);
<canvas id="canvas" width="512" height="256"></canvas>

【讨论】:

  • 盲人,我知道我不应该说“谢谢”,但我要去anwyay。我非常感谢您对示例解决方案的回答。非常感谢。
猜你喜欢
  • 2011-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-05
  • 2014-07-11
相关资源
最近更新 更多