这篇文章主要介绍了javascript+html5 canvas绘制的小人效果,涉及javascript结合html5 canvas图形绘制及颜色随机填充的技巧,需要的朋友可以参考下
本文实例讲述了javascript+html5 canvas绘制的小人效果。分享给大家供大家参考,具体如下:
运行效果截图如下:
index.html代码如下:
<!doctype html><html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <title>canvas中的缩放</title> <style type="text/css"> #canvas { background:black; margin-top:100px; margin-left:200px; } </style> </head> <body> <canvas id="canvas" width="500px" height="500px" ></canvas> </body> <script type="text/javascript" src="canvas.js"></script> <script type="text/javascript"> cache = {}; var offsetx = 50, offsety = 20; cache.context = dyl.createcontext('canvas'); dyl.rect(dyl.createcolor(), 60 + offsetx, 0 + offsety, 185, 100); dyl.rect(dyl.createcolor(), 100 + offsetx, 100 + offsety, 100, 50); dyl.rect(dyl.createcolor(), 20 + offsetx, 150 + offsety, 260, 200); dyl.rect(dyl.createcolor(), 80 + offsetx, 350 + offsety, 30, 110); dyl.rect(dyl.createcolor(), 190 + offsetx, 350 + offsety, 30, 110); dyl.circle(dyl.createcolor(), 115 + offsetx, 55, 20); dyl.circle(dyl.createcolor(), 190 + offsetx, 55, 20); </script></html>
canvas.js代码如下:
(function() { var dyl = {cache: {}}; dyl.setcontext = function(context) { dyl.cache._context = context; return context; } dyl.getdom = function(id) { return document.getelementbyid(id); } dyl._getcontext = function() { return dyl.cache._context; } dyl.save = function() { var context = dyl._getcontext(); context ? context.save() : void(0); } dyl.restore = function() { var context = dyl._getcontext(); context ? context.restore() : void(0); } dyl.createcontext = function(canvasid) { var canvas = this.getdom(canvasid); if(!canvas) { return null; } return dyl.setcontext(canvas.getcontext("2d")); } dyl.createcolor = function() { var color = "rgb("; color += math.round(math.random()*255); color += ","; color += math.round(math.random()*255); color += ","; color += math.round(math.random()*255); color += ")"; return color; }; dyl.addimg = function(img, x, y) { var context = dyl._getcontext(); if(!img || !context) { return; } if(typeof img === "string") { var oimg = new image(); oimg.src = img; oimg.onload = function() { context.drawimage(oimg, x, y); } return; } context.drawimage(img, x, y); }; dyl.rect = function(color, x, y, width, height) { var context = dyl._getcontext(); if(!context) { return; } context.fillstyle = color; context.fillrect(x, y, width, height); }; dyl.circle = function(color, x, y, r) { var context = dyl._getcontext(); context.save(); context.fillstyle = color; context.beginpath(); context.arc(x, y, r, 0, 2*math.pi); context.fill(); context.stroke(); }; dyl.scale = function(x, y) { var context = dyl._getcontext(); if(!context) { return; } x = x ? x : 1; y = y ? y : 1; context.scale(x, y); }; if(!window.dyl) { window.dyl = dyl; }})();
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注!
相关推荐:
原生js+canvas实现五子棋游戏的代码
使用纯js代码判断字符串中有多少汉字的方法
以上就是javascript+html5 canvas绘制小人的效果介绍的详细内容。