我试图在画布的弧形末端放置图像图标。在弧的起点和终点处。但是无法做到这一点。
我的js代码:
var coord=getPoint(x, y, radius, endAngle);
var img = new Image();
img.src = 'http://dailydropcap.com/images/D-6.jpg';
context.drawImage(img, coord.x, coord.y,'20px','20px');
context.stroke();
答案 0 :(得分:1)
您可以在弧上的任意角度获取XY,如下所示:
function xyOnArc(cx,cy,radius,radianAngle){
var x=cx+radius*Math.cos(radianAngle);
var y=cy+radius*Math.sin(radianAngle);
return({x:x,y:y});
}
演示:http://jsfiddle.net/m1erickson/C4Y3V/
以下是示例代码:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" 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 cx=100;
var cy=100;
var radius=40;
var startAngle=Math.PI/2;
var endAngle=Math.PI*2;
ctx.beginPath();
ctx.arc(cx,cy,radius,startAngle,endAngle);
ctx.stroke();
var start=xyOnArc(cx,cy,radius,startAngle);
ctx.fillStyle="blue";
ctx.fillRect(start.x,start.y,20,20);
var end=xyOnArc(cx,cy,radius,endAngle);
ctx.fillStyle="green";
ctx.fillRect(end.x,end.y,20,20);
function xyOnArc(cx,cy,radius,radianAngle){
var x=cx+radius*Math.cos(radianAngle);
var y=cy+radius*Math.sin(radianAngle);
return({x:x,y:y});
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
[添加:如何为图片添加图片时间]
var img = new Image();
img.onload=function(){
// img is now fully loaded
// do your drawImage inside this onload function
ctx.drawImage(img,x,y);
}
img.src = 'http://dailydropcap.com/images/D-6.jpg';