如何将画布内的多种形状中的一种移动50像素;

时间:2017-10-10 19:58:22

标签: javascript

我有一个项目要做,直到我理解了画布中的移动对象是如何工作之前我无法做到的。 我需要将下面的一个对象向右移动50像素。 任何愿意帮助我的人都非常感激。 同时非常感谢您的帮助或建议。

function canvasOneShape(){

//refers to the html canvasone id
var canvas = document.getElementById("canvasOne");
this.canvasOne.width = 945;
this.canvasOne.height = 650;
// draws the canvas in 2d
var ctx = canvas.getContext("2d");
// Set the fill colour to blue.
ctx.fillStyle = "blue"; //used like this instead of rgb due personal preference:)
// Create a filled rectangle at co-ordinates (10,10)
// with height and width set to 100.
ctx.fillRect(10, 10, 250, 330); //

// Here I draw the square
// Set the canvas up for drawing in 2D.
// Set the fill colour to blue.
ctx.fillStyle = "rgba(244, 244, 189,.5)";
ctx.fillRect(10, 50, 330, 250);

//draw my first circle
var midXone = canvas.width / 2;     //x location
var midXtwo = canvas.height / 2;    //y location
var radius = 60;                    //circle radius

ctx.beginPath();
ctx.arc(midXone, midXtwo, radius, 0, 2 * Math.PI, false);
ctx.fillStyle ="rgba(89, 192, 227,.4)";
ctx.fill();
ctx.lineWidth = 5;
ctx.strokeStyle = '#003300';
ctx.stroke();

//draw the second circle
var midX = canvas.width / 2.35;     //x location
var midY = canvas.height / 2.35;    //y location
var radius = 50;                    //circle radius
ctx.beginPath();
ctx.arc(midX, midY, radius, 0, 2 * Math.PI, false);
ctx.fillStyle ="rgba(66, 244, 89,.4)";
ctx.fill();
ctx.lineWidth = 5;
ctx.strokeStyle ="rgba(255, 244, 9,.4)";
ctx.stroke();

//draw Square with circle inside
//square
ctx.fillStyle = "rgb(222, 33, 51)";
ctx.fillRect(550, 20, 300, 300);
//circle

ctx.beginPath();
ctx.arc(700, 170, 150, 0, 2 * Math.PI, false);
ctx.fillStyle ="rgba(66, 244, 89,.4)";
ctx.fill();
ctx.lineWidth = 1;
ctx.strokeStyle = '#f44242';
ctx.stroke();

//The Pacman object

    var radius = 100;                   //circle radius
    var x = 100;
    var y = 500;
    ctx.beginPath();
    ctx.arc(120, 500, radius, 1.85 * Math.PI, .15 * Math.PI, true);

    //Draw mouth
    ctx.lineTo(120, 500);
    ctx.closePath();
    ctx.fillStyle = "rgb(255, 255, 0)";
    ctx.fill();
    ctx.lineWidth = 5;
    ctx.strokeStyle = 'rgb(0,0,0)';
    ctx.stroke();

    //draw eye
    ctx.beginPath();
    ctx.arc(x + 40, y - 40, 10, 0 * Math.PI, 2 * Math.PI, true);
    ctx.fillStyle = "rgb(0,0,0)";
    ctx.fill();

}

1 个答案:

答案 0 :(得分:0)

画布上没有图层或对象(它只是一层像素),因此,如果你画了一些东西,你就会覆盖它下面的内容。要向右移动某些东西,你需要有一个函数来绘制它背后的所有东西,然后变量来存储你想要移动的对象的位置(x和y)。 然后,要移动它,你用
清除画布  ctx.clearRect(0, 0,width of canvas, height height of canvas);, 调用背景函数再次绘制背后的所有内容,并将对象重新绘制在不同的位置。