San*_*nne 11 javascript html5 canvas
我使用fillText选项在html5画布对象上放置了一个文本,问题是我需要移动文本位置或更改已经渲染的文本的颜色.
不久我需要知道如何操作canvas元素的特定子元素
这会在画布上移动一个小圆圈
var can = document.getElementById('canvas');
can.height = 1000; can.width = 1300;
var ctx = can.getContext('2d');
var x = 10, y = 100;
ctx.fillStyle = "black";
ctx.fillRect(700, 100, 100, 100);
function draw() {
ctx.beginPath();
ctx.arc(x, y, 20, 0, 2 * Math.PI);
ctx.fillStyle = 'rgba(250,0,0,0.4)';
ctx.fill();
x += 2;
ctx.fillStyle = "rgba(34,45,23,0.4)";
ctx.fillRect(0, 0, can.width, can.height);
requestAnimationFrame(draw);
//ctx.clearRect(0,0,can.width,can.height);
}
draw();Run Code Online (Sandbox Code Playgroud)
<canvas id="canvas" style="background:rgba(34,45,23,0.4)"></canvas>Run Code Online (Sandbox Code Playgroud)
我认为画布背后没有对象模型,所以你不能像"文本对象"那样访问"子对象"并进行更改.你可以做的是用不同的颜色再次绘制文本,覆盖画布的"像素".如果要移动文本,首先必须清除画布或使用背景/透明颜色重新绘制文本以删除前一个位置的文本.然后,您可以在新位置绘制文本.
我从未尝试过,但我认为这就是实现这一目标的方法。
var canvas = document.getElementById("canvas"); //get the canvas dom object
var ctx = canvas.getContext("2d"); //get the context
var c = { //create an object to draw
x:0, //x value
y:0, //y value
r:5; //radius
}
var redraw = function(){ // this function redraws the c object every frame (FPS)
ctx.clearRect(0, 0, canvas.width, canvas.height); // clear the canvas
ctx.beginPath(); //start the path
ctx.arc(c.x, c.y, c.r, 0, Math.PI*2); //draw the circle
ctx.closePath(); //close the circle path
ctx.fill(); //fill the circle
requestAnimationFrame(redraw);//schedule this function to be run on the next frame
}
function move(){ // this function modifies the object
var decimal = Math.random() // this returns a float between 0.0 and 1.0
c.x = decimal * canvas.width; // mulitple the random decimal by the canvas width and height to get a random pixel in the canvas;
c.y = decimal * canvas.height;
}
redraw(); //start the animation
setInterval(move, 1000); // run the move function every second (1000 milliseconds)
Run Code Online (Sandbox Code Playgroud)
这是一个小提琴。 http://jsfiddle.net/r4JPG/2/
如果您需要缓动和平移,请move相应地更改方法。
| 归档时间: |
|
| 查看次数: |
67688 次 |
| 最近记录: |