关键词搜索

源码搜索 ×
×

canvas笔记-扩展canvas的context及画椭圆及浏览器兼容问题

发布2020-06-03浏览1308次

详情内容

首先是扩展canvas的context

比如扩展一个画五角星的代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <canvas id="canvas" style="border: 1px solid #aaa; display: block; margin: 50px auto;">
  9. 当前浏览器不支持canvas
  10. </canvas>
  11. <script>
  12. CanvasRenderingContext2D.prototype.fillStar = function(r, R, x, y, rot){
  13. this.beginPath();
  14. for(let i = 0; i < 5; i++){
  15. this.lineTo(Math.cos((18 + i * 72 - rot) / 180 * Math.PI) * R + x,
  16. -Math.sin((18 + i * 72 - rot) / 180 * Math.PI) * R + y);
  17. this.lineTo(Math.cos((54 + i * 72 - rot) / 180 * Math.PI) * r + x,
  18. -Math.sin((54 + i * 72 - rot) / 180 * Math.PI) * r + y);
  19. }
  20. this.closePath();
  21. this.fill();
  22. }
  23. window.onload = function(){
  24. let canvas = document.getElementById("canvas");
  25. canvas.width = 800;
  26. canvas.height = 800;
  27. let context = canvas.getContext("https://cdn.jxasp.com:9143/image/2d");
  28. context.fillStyle = "#087";
  29. context.fillStar(150, 300, 400, 400, 0);
  30. }
  31. </script>
  32. </body>
  33. </html>

运行截图如下:

通过CanvasRenderingContext2D.prototype中定义函数可实现扩展。

 

下面是画椭圆,程序运行截图如下:

源码如下:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <canvas id="canvas" style="border: 1px solid #aaa; display: block; margin: 50px auto;">
  9. 当前浏览器不支持canvas
  10. </canvas>
  11. <script>
  12. window.onload = function(){
  13. let canvas = document.getElementById("canvas");
  14. canvas.width = 800;
  15. canvas.height = 800;
  16. let context = canvas.getContext("https://cdn.jxasp.com:9143/image/2d");
  17. if(context.ellipse){
  18. context.beginPath();
  19. context.ellipse(400, 400, 300, 200, 0, 0, Math.PI * 2);
  20. context.stroke();
  21. }
  22. else{
  23. alert("no ellipse");
  24. }
  25. }
  26. </script>
  27. </body>
  28. </html>

 

下面是兼容性问题,就是这段代码:

  1. if(context.ellipse){
  2. context.beginPath();
  3. context.ellipse(400, 400, 300, 200, 0, 0, Math.PI * 2);
  4. context.stroke();
  5. }
  6. else{
  7. alert("no ellipse");
  8. }

如果浏览器不支持context.ellipse那么值会为undefined,这样就会进入else里面。

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载