canves的常用方法
Posted 专注于技术的小石头
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了canves的常用方法相关的知识,希望对你有一定的参考价值。
1.获取一个圆的某个角度的位置
function circlePosition(center,du,r){ var cx=Math.sin(du*2*Math.PI / 360) * r ; var cy=Math.cos(du*2*Math.PI / 360) * r ; var ax = center.x+cx; var ay = center.y+cy; return {x:ax,y:ay}; }
2.canves 2D扩展 绘制圆角矩形的方法
CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) { if (w < 2 * r) r = w / 2; if (h < 2 * r) r = h / 2; this.beginPath(); this.moveTo(x+r, y); this.arcTo(x+w, y, x+w, y+h, r); this.arcTo(x+w, y+h, x, y+h, r); this.arcTo(x, y+h, x, y, r); this.arcTo(x, y, x+w, y, r); this.closePath(); return this; } 用法: context.roundRect(x,y,w,h,r).stroke();
3.canvas 的常用事function windowToCanvas(canvas,x,y){
var bbox = canvas.getBoundingClientRect(); return { x:x - bbox.left - (bbox.width - canvas.width) / 2, y:y - bbox.top - (bbox.height - canvas.height) / 2 }; }
canvas.onmousedown=function(event){ var pos=windowToCanvas(canvas,event.clientX,event.clientY); } canvas.onmouseup=function(){ //canvas.onmousemove=null; canvas.onmouseup=null; canvas.style.cursor="default"; } canvas.onmousemove=function(event){ canvas.style.cursor="move"; var pos=windowToCanvas(canvas,event.clientX,event.clientY); } canvas.onmousewheel=canvas.onwheel=function(event){ var pos=windowToCanvas(canvas,event.clientX,event.clientY); event.wheelDelta=event.wheelDelta?event.wheelDelta:(event.deltaY*(-40)); if(event.wheelDelta>0){ }else{ } }
4.canvas 画线
function drawLine(x,y,x1,y1){ context.lineWidth = "0.5"; context.beginPath(); context.strokeStyle="#569CD6"; context.moveTo(x,y); context.lineTo(x1,y1); context.closePath(); context.stroke(); }
5.canvas 画圆
function drawCircle(x,y,r){ context.beginPath(); context.lineWidth="0.5"; context.arc(x,y,r,0,2*Math.PI); context.stroke(); context.closePath(); }
6.canvas画文字(带自动换行)
function drawText(x,y,lingH,color,str){ context.font="12px Verdana"; context.fillStyle="#F2F2F2"; var lineWidth = 0; var canvasWidth = nodeWith-30; var initHeight=20;//绘制字体距离canvas顶部初始的高度 var lastSubStrIndex= 0; //每次开始截取的字符串的索引 for(let i=0;i<str.length;i++){ lineWidth+=ctx.measureText(str[i]).width; if(lineWidth>canvasWidth){ context.fillText(str.substring(lastSubStrIndex,i),x+5,y+initHeight);//绘制截取部分 initHeight+=15;//20为字体的高度 lineWidth=0; lastSubStrIndex=i; } if(i==str.length-1){//绘制剩余部分 context.fillText(str.substring(lastSubStrIndex,i+1),x+5,y+initHeight); } } }
以上是关于canves的常用方法的主要内容,如果未能解决你的问题,请参考以下文章