HTML5 canvas绘图基础(电子名片生成器源码)

HTML5 canvas绘图基础(电子名片生成器源码),第1张

概述创建canvas <canvas id="myCanvas" class="canvas"> 您的浏览器不支持canvas </canvas&

创建canvas

  <canvas ID="myCanvas" class="canvas">    您的浏览器不支持canvas  </canvas>

基础设置

    <script type="text/JavaScript">        var canvas = document.getElementByID('myCanvas');        var ctx = canvas.getContext('2d');        canvas.wIDth=100;        canvas.height=100;    </script>

画直线
moveto(x1,y1)
lineto(x2,y2)

    ctx.moveto(0,0);    ctx.lineto(100,100);    ctx.stroke();

画圆形
ctx.arc(x,y,radius,2*Math.PI,true)

    ctx.beginPath();    ctx.arc(300,300,50,true);    ctx.strokeStyle = '#000';    ctx.stroke();

画矩形
ctx.strokeRect(x1,y1,x2,y2)

    ctx.strokeRect(300,100,200,100);

beginPath()开始一条新路径
closePath()使当前路径闭合
不是成对出现的

      ctx.beginPath();      ctx.moveto(300,1)">);      ctx.lineto(200,200);      ctx.closePath();      ctx.strokeStyle = '#0F0';      ctx.stroke();

设置样式

      ctx.moveto(0,1)">);      ctx.lineto(100,1)">);      ctx.closePath();      //linewidth 设置描边的线宽      ctx.linewidth = 10;      strokeStyle 设置描边样式      ctx.strokeStyle = "#F00";      ctx.stroke();      fillStyle 设置填充样式      ctx.fillStyle = "rgba(0,0.5)";      ctx.fill();

绘制矩形与样式同步

      ctx.strokeRect(100,1)">);      ctx.fillRect(100,100);

保存和恢复上下文环境,一般成对出现
save 保存当前绘画环境,包括变换和样式
restore 恢复当前绘画环境,包括变换和样式

   ctx.save();   ctx.restore();

图形变换

      translate 平移变换      ctx.translate(0,1)">);      ctx.beginPath();      ctx.moveto(0,1)">);      ctx.stroke();      rotate 旋转变换      ctx.rotate(Math.PI/4);      ctx.beginPath();      ctx.moveto(0,1)">);      ctx.linewidth = 5;      ctx.strokeStyle = "#F00";      ctx.stroke();      scale 缩放变换      ctx.scale(1,0.5);      ctx.fillRect(0,-100,100);

线性渐变

        var linearGradIEnt = ctx.createlinearGradIEnt(0,1)">给渐变添加颜色        linearGradIEnt.addcolorStop(0,'rgb(255,0)');        linearGradIEnt.addcolorStop(0.3,'rgb(0,1)">);        linearGradIEnt.addcolorStop(1,255)'设置渐变作为样式        ctx.fillStyle = linearGradIEnt;        ctx.fillRect(0,200);

径向渐变

        var radialGradIEnt = ctx.createradialGradIEnt(400,400,150,1)">);        radialGradIEnt.addcolorStop(0,1)">);        radialGradIEnt.addcolorStop(1,1)">);        ctx.fillStyle = radialGradIEnt;        ctx.beginPath();        ctx.arc(400,Math.PI * 2,1)">);        ctx.fill();

文字

字体若设置了居中,圆心会在文字的中间位置,所以圆心还是要根据画布大小和文字的宽度进行设置。

        var str = "hello world";        设置文本样式,比如大小,字体        ctx.Font = "50px sans-serif"水平对其设置,left center right        ctx.textAlign = "center"垂直对齐设置,top mIDdle bottom        ctx.textBaseline = "top"填充文本        ctx.fillText(str,1)">描边文本        ctx.strokeText(str,1)">获取文本宽度        var wIDth = ctx.measureText(str).wIDth;        console.log(wIDth);

图片

        ctx.fillRect(0,1)">,canvas.wIDth,canvas.height);        var img = new Image();        img.src = "logo.png"一定要在图像加载完成后的回调中绘制图像        img.onload = function () {            在(0,0)点处绘制img图像             ctx.drawImage(img,0);                        获取img图像的(0,0)点处的40*40区域,绘制在(100,100)点处,缩放成80*80            ctx.drawImage(img,40,80,80);        }

创建图像画刷ctx.createPattern(image,type)

        ctx.fillRect(0,1)">;        img.onload = 创建图像画刷,no-repeat,repeat-x,repeat-y,repeat            var pattern = ctx.createPattern(img,"repeat");            ctx.fillStyle = pattern;            ctx.fillRect(0,canvas.height);        }

阴影绘制

        阴影的X偏移        ctx.shadowOffsetX = 10阴影的Y偏移        ctx.shadowOffsetY = 10阴影的颜色        ctx.shadowcolor = 'rgba(0,0.5)'阴影的模糊度        ctx.shadowBlur = 10;        ctx.fillStyle = 'rgba(255,1)">;        ctx.fillRect(100,1)">);        ctx.Font = "50px sans-serif";        ctx.fillText("我是小可爱",100);

区域剪辑

    保存当前环境    ctx.save();    ctx.arc(300,Math.PI*2,1)">);    进行区域剪辑    ctx.clip();    ctx.fillStyle = "#F00";    ctx.fillRect(100,1)">恢复环境,释放了剪辑区域的作用    ctx.restore();

绘制曲线ctx.arc(x,startAngle,endAngle,true)
最后一个参数代表是否是逆时针方向

        绘制圆弧        ctx.arc(100,1)">);        ctx.fill();        二次样条曲线ctx.quadraticCurveto(qcpx,qcpy,qx,qy)        ctx.beginPath();        ctx.moveto(100,355);        ctx.quadraticCurveto(265,145,380,349贝塞尔曲线ctx.bezIErCurveto(cp1x,cp1y,cp2x,cp2y,x,y)        ctx.beginPath();        ctx.moveto(175,375);        ctx.bezIErCurveto(297,182,468,252,517,380);        ctx.fill();

canvas绘制曲线生成工具
两次贝塞尔曲线:
http://blogs.sitepointstatic.com/examples/tech/canvas-curves/quadratic-curve.HTML
三次贝塞尔曲线:
http://blogs.sitepointstatic.com/examples/tech/canvas-curves/bezIEr-curve.HTML

 

动画

ctx.clearRect(x,wIDth,height) 清除区域,用于重新绘制

        var posx = 0,posy = 0,dir = 1,isMouseInRect = false;         确定动画范围        canvas.onmousemove = (e){            var mouseX = e.offsetX;            var mouseY = e.offsetY;            if(mouseX > posx && mouseY <posx +50 && mouseY > posy && mouseY < posy+ 50){                isMouseInRect = ;            }else{                isMouseInRect = ;            }        }         开始动画        setInterval(() {            if(!isMouseInRect){                posx += 10 * dir;            }            clearRect清空画布的一个矩形区域            ctx.clearRect(0,canvas.height);            ctx.fillRect(posx,posy,50,50);            if(posx + 50 >= canvas.wIDth){                dir = -1else if(posx <= 0){                dir = 1;            }        },100);

离屏技术
把canvas(sx,sy)处宽sw,高sy的区域,绘制到(dx,dy)处,并缩放为宽dx,高dh
ctx.drawImage(canvas,sx,sy,sw,sh,dx,dy,DW,dh)

<!DOCTYPE HTML>HTML lang="en"head>  Meta charset="UTF-8" />  Title>canvasstyle type="text/CSS">    canvas {      border: 1px solID red;    }    #offCanvas      display none}  stylebody>      wIDth="600px" height="400px"      您的浏览器不支持canvas    <!--创建离屏Canvas-->    ="offCanvas"script  ="text/JavaScript">        var canvas = document.getElementByID('myCanvas);         ctx  canvas.getContext(2d);         offCanvas offCanvas offCtx  offCanvas.getContext( posx = 01false;        //把一些复杂的绘画 *** 作,画在离屏Canvas上面         drawALot function(){            for( k; k<20++){                 i;icanvas.wIDth;i+=10){                     j;jcanvas.height;j){                        offCtx.beginPath();                        offCtx.arc(i,j,52*Math.PI,1)">true);                        offCtx.stroke();                    }                }            }        }        canvas.onmousemove (e){             mouseX  e.offsetX;             mouseY  e.offsetY;            if(mouseX &&posx +50  posy + 50){                isMouseInRect ;            }else{                isMouseInRect ;            }        }        setInterval(() {            !isMouseInRect){                posx += 10  dir;            }            clearRect清空画布的一个矩形区域            ctx.clearRect( drawALot();            真正要用到复杂的绘画的时候,直接从离屏Canvas上拷贝过来            ctx.drawImage(offCanvas,offCanvas.wIDth,offCanvas.height,1)">);            (posx >= canvas.wIDth){                dir -else <= ){                dir 100);        drawALot();    scriptHTML>

案例:电子名片生成器

index.HTML

="utf-8" >电子名片生成器link href="style/style.CSS" rel="stylesheet" />div class="left-div"="line">      input ="name" type="text" placeholder="姓名"/>    div="address"="地址"="job"="职业"="slogan"="口号" button ="generateBtn">生成名片button="right-div"="cardCanvas"      您的浏览器不支持Canvas,请升级浏览器    ="animCanvas"script src="script/main.Js"></>

style.CSS

* {  margin: 0;  padding: 0;}HTML,body {  height: 100%;}.left-div {  wIDth: 30%; 100%;  float: left;  background: #a4a296;}.line {  text-align: center;  margin-top: 30px;}.line:first-child { 200px;}.line span {  color: white;}.line input { 300px; 30px;  border-radius: 15px;  padding-left:  outline: none;  border: none;}.line button { 100px; #222; #DDD;  cursor: pointer;  position: relative; 15px;}.line button:hover { #000; #FFF;}.line button:active {  left: 1px;  top: 1px;}.right-div { 70%; #eee9d3; relative;}.right-div canvas { absolute; 200px; 50%;  margin-left: -300px;}#cardCanvas {  display: none;}

main.Js

 创建和设置cardCanvas,该canvas作为离屏canvasvar cardCanvas = document.getElementByID('cardCanvas');var cardCtx = cardCanvas.getContext('2d');cardCtx.canvas.wIDth = 600;cardCtx.canvas.height = 100; 加载图片 Image();img.src = "images/logo.png";img.onload = () {  cardCtx.drawImage(img,10,10);}var generateBtn = document.getElementByID("generateBtn");generateBtn.onclick = () {  cardCtx.clearRect(0,cardCtx.canvas.wIDth,cardCtx.canvas.height);   背景的线性渐变  var linearGradIEnt = cardCtx.createlinearGradIEnt(0,cardCtx.canvas.height);  linearGradIEnt.addcolorStop(0.5,1)">);  linearGradIEnt.addcolorStop(1,'rgb(133,133,133)');  cardCtx.fillStyle = linearGradIEnt;  cardCtx.fillRect(0,1)"> logo图像  cardCtx.drawImage(img,10,1)">);   获取姓名、地址、职业,绘制,并计算长度  var name = document.getElementByID("name").value || "请输入姓名";  var address = document.getElementByID("address").value || "请输入地址"var job = document.getElementByID("job").value || "请输入职业"var nameWIDth,addressWIDth,jobWIDth,maxWIDth = 0;  cardCtx.Font = "bold 30px sans-serif";  cardCtx.fillStyle = "#fff";  cardCtx.fillText(name,105,35);  nameWIDth = cardCtx.measureText(name).wIDth;  cardCtx.Font = "bold 20px sans-serif";  cardCtx.fillText(address,60);  cardCtx.fillText(job,85);  addressWIDth = cardCtx.measureText(address).wIDth;  jobWIDth = cardCtx.measureText(job).wIDth;  if(maxWIDth < nameWIDth) {    maxWIDth = nameWIDth;  }   addressWIDth) {    maxWIDth = addressWIDth;  }   jobWIDth) {    maxWIDth = jobWIDth;  }   绘制口号  var slogan = document.getElementByID("slogan").value || "请输入口号";  cardCtx.save();   做图形变换  cardCtx.rotate(-0.1);  cardCtx.translate(0,1)"> 阴影  cardCtx.shadowOffsetX = 10;  cardCtx.shadowOffsetY = 10;  cardCtx.shadowcolor = 'rgba(0,1)">;  cardCtx.shadowBlur = 1.5;  cardCtx.fillStyle = "#ddd" 计算口号位置  var solganWIDth;  solganWIDth = cardCtx.measureText(slogan).wIDth;  var offset = (cardCtx.canvas.wIDth - 115 - maxWIDth - solganWIDth) / 2;  cardCtx.fillText(slogan,115 + maxWIDth + offset,1)"> 画曲线  cardCtx.beginPath();  cardCtx.moveto(115 + maxWIDth + offset,70);  cardCtx.quadraticCurveto(115 + maxWIDth + offset,115 + solganWIDth + maxWIDth + offset,1)">);  cardCtx.strokeStyle = "#ddd";  cardCtx.stroke();  cardCtx.restore();} 触发click事件generateBtn.click(); 创建和设置animCanvas,该canvas才是真正的显示var animCanvas = document.getElementByID('animCanvas'var animCtx = animCanvas.getContext('2d');animCtx.canvas.wIDth = 600;animCtx.canvas.height = 100var circles = [];setInterval(() {   擦出画布  animCtx.clearRect(0,animCtx.canvas.wIDth,animCtx.canvas.height);   把离屏canvas的内容画进来  animCtx.drawImage(cardCanvas,animCtx.canvas.height,0,1)"> 绘制下落的圆形  for(var i=0; i<=10; i++) {    circles[i]) {      circles[i] = {};      circles[i].radius = Math.floor(Math.random() * 5) + 1;      circles[i].y = - circles[i].radius - Math.floor(Math.random() * 10);      circles[i].x = i * 60 + Math.floor(Math.random() * 10) - 5;      circles[i].vy = Math.floor(Math.random() * 5) + 1;    }    animCtx.beginPath();    animCtx.arc(circles[i].x,circles[i].y,circles[i].radius,Math.PI * 2);    animCtx.fillStyle = "rgba(255,1)">;    animCtx.fill();    circles[i].y = circles[i].y + circles[i].vy;    if(circles[i].y > animCtx.canvas.height + circles[i].radius * 2) {      circles[i] = undefined;    }  }},100);

案例:山中明月风景图

>document        canvasbackground-color#000;opacity0.7}    ="canvas" wIDth="720px"="600px">您的浏览器不支持canvas canvasdocument.getElementByID("canvas contextcanvas.getContext( 月亮绘制        context.shadowOffsetX;        context.shadowOffsetY;        context.shadowBlur;        context.shadowcolorrgba(255,0.2);        context.fillStyleyellow;        context.arc(40);        context.fill();         文字绘制        context.beginPath();         str山高月小;        context.Font50px 宋体#fff;        context.fillText(str,1)">400200 山峰绘制        context.beginPath();        context.linewidth;        context.strokeStylelightblue;        context.moveto(14600);        context.quadraticCurveto(60193123);        context.stroke();        context.beginPath();        context.moveto(298);        context.bezIErCurveto(817369150045134273361452569210695426715);        context.stroke();    >
总结

以上是内存溢出为你收集整理的HTML5 canvas绘图基础(电子名片生成器源码)全部内容,希望文章能够帮你解决HTML5 canvas绘图基础(电子名片生成器源码)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1026486.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存