关键词搜索

源码搜索 ×
×

canvas笔记-使用canvas画矩形及各样式(透明)

发布2020-05-31浏览3256次

详情内容

程序运行截图如下:

源码如下:

  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. drawRect(context, 100, 100, 400, 400, 10, "#508", "red");
  18. drawFillRect(context, 200, 200, 400, 400, 10, "#508", "blue");
  19. drawFillRect(context, 300, 300, 400, 400, 10, "#508", "rgba(255, 255, 0, 0.5)")
  20. }
  21. function drawRect(cxt, x, y, width, height, borderWidth, borderColor, fillColor){
  22. cxt.beginPath();
  23. cxt.rect(x, y, width, height);
  24. cxt.closePath();
  25. cxt.lineWidth = borderWidth;
  26. cxt.fillStyle = fillColor;
  27. cxt.strokeStyle = borderColor;
  28. cxt.fill();
  29. cxt.stroke();
  30. }
  31. function drawFillRect(cxt, x, y, width, height, borderWidth, borderColor, fillColor){
  32. cxt.lineWidth = borderWidth;
  33. cxt.fillStyle = fillColor;
  34. cxt.strokeStyle = borderColor;
  35. cxt.fillRect(x, y, width, height);
  36. cxt.strokeRect(x, y, width, height);
  37. }
  38. </script>
  39. </body>
  40. </html>

画矩形有两种:

一种是:使用

rect()函数画出框,然后使用:

  1. cxt.lineWidth = borderWidth;
  2. cxt.fillStyle = fillColor;
  3. cxt.strokeStyle = borderColor;
  4. cxt.fill();

这些进行填充。

第二种是使用:

  1. function drawFillRect(cxt, x, y, width, height, borderWidth, borderColor, fillColor){
  2. cxt.lineWidth = borderWidth;
  3. cxt.fillStyle = fillColor;
  4. cxt.strokeStyle = borderColor;
  5. cxt.fillRect(x, y, width, height);
  6. cxt.strokeRect(x, y, width, height);
  7. }

这种方式进行绘制。

关于透明相关的:

cxt.fillStyle = fillColor;

可以通过传入rgba(255, 255, 0, 0.5)这种方式设置透明度。

 

相关技术文章

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

提示信息

×

选择支付方式

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