gpt4 book ai didi

javascript - 单击图像添加到 HTML5 Canvas 路径

转载 作者:行者123 更新时间:2023-12-02 17:51:41 24 4
gpt4 key购买 nike

我正在 html5 Canvas 上画一个圆圈,如下所示:

<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 70;

context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.lineWidth = 1;
context.strokeStyle = '#000000';
context.stroke();
</script>
</body>
</html>

在我的网站上,我在 Canvas 左侧有一系列图像,用户单击它们,会将图像添加到 Canvas 中并且可以拖动。我正在使用 KineticJS 来实现这部分。我需要帮助了解如何单击图像并将图像添加到圆圈的边界并且仅沿着圆圈移动。在 KineticJS 网站上,他们有一个功能,允许用户以圆周运动拖动。我不想使用它,因为它只是将其限制在整个圆上,并且我希望它围绕圆的边界。下面是我要问的图片: circular drag http://www.papiobeads.com/images/theimage.png

最佳答案

您可以使用 Canvas 变换来围绕圆的圆周旋转图像。

  • 移动到您想要的旋转点(圆的中心)
  • 设置所需的旋转 Angular (以弧度为单位)
  • 绘制图像

enter image description here enter image description here

这里是示例代码和演示:http://jsfiddle.net/m1erickson/t5N9T/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
<script src="http://code.jquery.com/jquery.min.js"></script>

<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>

<script>
$(function(){

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

var radianAngle=0;
var cx=150;
var cy=150;
var radius=50;

var img=new Image();img.onload=start;img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/cars.png";
function start(){
animate();
}

function animate() {
requestAnimationFrame(animate);

// Drawing code goes here
radianAngle+=Math.PI/120;
ctx.clearRect(0,0,canvas.width,canvas.height);
// draw the circle
ctx.beginPath();
ctx.arc(cx,cy,radius,0,Math.PI*2);
ctx.closePath();
ctx.stroke();
// draw the image rotated around the circumference
ctx.save();
ctx.translate(cx,cy);
ctx.rotate(radianAngle);
ctx.drawImage(img,radius-img.width/2,-img.height/2);
ctx.restore();
}

}); // end $(function(){});
</script>

</head>

<body>
<canvas id="canvas" width=350 height=350></canvas>
</body>
</html>

关于javascript - 单击图像添加到 HTML5 Canvas 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21293797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com