HTML5 Canvas实现图片缩放、翻转、颜色渐变的代码示例
2021-05-08 21:12:15 翻转、移动、平移、放大、缩小
XML/HTML Code复制内容到剪贴板varcanvas=document.getElementById('canvas');if(canvas.getContext){varcontext=canvas.getContext('2d');//放大与缩小context.beginPath();context.strokeStyle="#000000";context.strokeRect(10,10,150,100);//放大3倍context.scale(3,3);context.beginPath();context.strokeStyle='#cccccc';context.strokeRect(10,10,150,100)//缩小context.scale(0.5,0.5);context.beginPath();context.strokeStyle='#cccccc';context.strokeRect(10,10,150,100)//翻转varimg=newImage();img.src='images/1.jpg';img.onload=function(){context.drawImage(img,10,10);context.scale(1,-1);context.drawImage(img,0,-500);}//平移context.beginPath();context.strokeStyle='#000000';context.strokeRect(10,101,150,100);//x移动50y移动100context.translate(50,100);context.beginPath();context.strokeStyle='#cccccc';context.strokeRect(10,10,150,100);//旋转context.beginPath();context.strokeStyle='#000000';context.strokeRect(200,50,100,50);//默认旋转是根据0,0中心,使用translate可以按照自己的设置的中心旋转context.translate(250,75);context.rotate(45*Math.PI/180);context.translate(-250,-75);context.beginPath();context.strokeStyle='#cccccc';context.strokeRect(200,50,100,50);//transform矩阵context.beginPath();context.strokeStyle='#000000';context.strokeRect(10,10,150,100);context.transform(3,0,0,3,0,0);context.beginPath();context.strokeStyle='#cccccc';context.strokeRect(10,10,150,100);}渐变、图像组合效果、颜色翻转
XML/HTML Code复制内容到剪贴板
varcanvas=document.getElementById('canvas');if(canvas.getContext){varcontext=canvas.getContext('2d');//线性绘制渐变vargrd=context.createLinearGradient(0,0,200,100);//postion必须是0.1-1.0之间的竖直,表示渐变中颜色的地点相对地位,color表示颜色grd.addColorStop(0.1,"#00ff00");grd.addColorStop(0.8,"#ff0000");context.fillStyle=grd;context.fillRect(0,0,200,100);//径向渐变vargrd=context.createRadialGradient(100,100,10,100,100,50);grd.addColorStop(0.1,"#00ff00");grd.addColorStop(0.8,'#ff0000');context.fillStyle=grd;context.fillRect(0,0,200,200);//图像组合效果context.fillStyle='#00ff00';context.fillRect(10,10,50,50);//新绘图//context.globalCompositeOperation="source-over";//只绘制新内容,删除其他所有内容context.globalCompositeOperation='copy';//图形重叠的地方,其颜色值相减后决定context.globalCompositeOperation='darker';//画布上已经有的内容只会载和其他图形重叠的地方保留context.globalCompositeOperation='destination-atop';//参考http://www.w3school.com.cn/htmldom/prop_canvasrenderingcontext2d_globalcompositeoperation.aspcontext.beginPath();context.fillStyle='#ff0000';context.arc(50,50,30,0,2*Math.PI);context.fill();//颜色翻转varimg=newImage();img.src='images/1.jpg';img.onload=function(){context.drawImage(img,0,0,1,1);varimgData=context.getImageData(0,0,1,1);varpixels=imgData.data;console.log(pixels);for(vari=0,n=pixels.length;i<n;i+=4){pixels[i]=255-pixels[i];pixels[i+1]=255-pixels[i+1];pixels[i+2]=255-pixels[i+2];}context.putImageData(imgData,250,0);}} 声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。 如涉及版权问题,请提交至online#300.cn邮箱联系删除。