【H5 Canvas 和 JavaScript 绘制sin曲线】

本文展示了如何利用HTML5 Canvas结合JavaScript来绘制并动态更新sin曲线。通过循环绘制不同位置的小圆点,形成沿sin曲线运动的效果。源代码中详细解释了关键函数如`drawSin`、`setCanvas`、`drawPoint`和`drawOneMoment`的实现,这些函数用于绘制曲线、设置定时更新以及创建动图效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

随机变换颜色的小圆球,沿着sin曲线运动。
源代码如下:

canvas class=“canvas” id=“canvas” width=“400” height=“400”
style=“border:1px solid #0000FF;”>

function drawSin (){
ctx.moveTo(0, 200);
for (var i=0;i<400;i++){
var y = i/10;
var z = 100*Math.sin(y) +200;
console.log(i);
console.log(z);
ctx.lineTo(i, z);
}
ctx.lineWidth = 2; //线宽
ctx.strokeStyle = ‘red’; //描边颜色
ctx.stroke(); //渲染直线(描边)
}

function setCanvas(){
ctx.clearRect(0, 0, 400, 400);
drawSin();
setInterval(‘drawOneMoment()’, 200);
}

//绘制某一时刻的点
function drawPoint(ctx, text, textcolor) {
var y = _i/10;
var z = 100*Math.sin(y) +200;
ctx.beginPath();
//画小圆点
ctx.moveTo(0, 410);
ctx.arc(_i, z, 8, 0, 2 * Math.PI, false);
var color = Math.floor(Math.random()*16777215);
var style = “#”+color.toString(16);
ctx.fillStyle= style;
ctx.fill();
ctx.closePath();

<
很多人都使用HTML5 Canvas来创建吊钩抓取的动画程序。这种程序通常使用JavaScript来控制画布上的对象,使用鼠标或触摸屏幕来控制吊钩的位置角度,并在画布上显示抓取过程。以下是一个简单的示例程序: ``` <!DOCTYPE html> <html> <head> <title>Hook Catch Animation</title> <style> canvas { border: 1px solid black; } </style> </head> <body onload="start()"> <canvas id="canvas" width="400" height="400"></canvas> <script> var canvas, ctx, hookX, hookY, angle, speed, dt; function start() { canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); hookX = canvas.width/2; hookY = 50; angle = Math.PI/2; speed = 100; dt = 0.01; draw(); } function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); drawHook(); drawBox(); moveHook(); requestAnimationFrame(draw); } function drawHook() { ctx.beginPath(); ctx.moveTo(hookX, hookY); ctx.lineTo(hookX + 20*Math.cos(angle), hookY + 20*Math.sin(angle)); ctx.stroke(); } function drawBox() { ctx.fillRect(canvas.width/2 - 25, canvas.height - 50, 50, 50); } function moveHook() { if (hookY < canvas.height - 50) { hookY += speed*dt; angle += 0.1*dt; } else { speed = 0; } } canvas.addEventListener("mousemove", function(event) { hookX = event.clientX - canvas.offsetLeft; hookY = event.clientY - canvas.offsetTop; angle = Math.atan2(hookY - 50, hookX - canvas.width/2); speed = 100; }); </script> </body> </html> ``` 这个程序使用Canvas绘制了一个吊钩一个方块,当鼠标在画布上移动时,吊钩跟随鼠标位置移动,并在方块上抓取。程序还包括一些基本的物理模拟来模拟吊钩的动作。你可以根据自己的需要修改程序,添加更多的特性效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值