HTML5 Canvas custom rounded rectangle and dotted Line (RoundedRectangle and Dash Line) to add a custom function to the HTML Canvas 2d context painting object demonstration, how to draw a dotted Line and control the dotted Line interval, learn how to draw a rounded rectangle. The native function provided in HTML5 Canvas painting objects does not provide the ability to draw rounded rectangle and dotted line. However, the Object. prototype in JavaScript can add these two functions to the Object CanvasRenderingContext2D. The demo of the Code is as follows:
The code for component fishcomponent. js is as follows:
CanvasRenderingContext2D.prototype.roundRect =function(x, y, width, height, radius, fill, stroke) {if (typeof stroke == "undefined") {stroke = true;}if (typeof radius === "undefined") {radius = 5;}this.beginPath();this.moveTo(x + radius, y);this.lineTo(x + width - radius, y);this.quadraticCurveTo(x + width, y, x + width, y + radius);this.lineTo(x + width, y + height - radius);this.quadraticCurveTo(x + width, y + height, x + width - radius, y+ height);this.lineTo(x + radius, y + height);this.quadraticCurveTo(x, y + height, x, y + height - radius);this.lineTo(x, y + radius);this.quadraticCurveTo(x, y, x + radius, y);this.closePath();if (stroke) {this.stroke();}if (fill) {this.fill();}};CanvasRenderingContext2D.prototype.dashedLineTo = function (fromX, fromY, toX, toY, pattern) {// default interval distance -> 5pxif (typeof pattern === "undefined") {pattern = 5;}// calculate the delta x and delta yvar dx = (toX - fromX);var dy = (toY - fromY);var distance = Math.floor(Math.sqrt(dx*dx + dy*dy));var dashlineInteveral = (pattern <= 0) ? distance : (distance/pattern);var deltay = (dy/distance) * pattern;var deltax = (dx/distance) * pattern;// draw dash linethis.beginPath();for(var dl=0; dl<dashlineInteveral; dl++) {if(dl%2) {this.lineTo(fromX + dl*deltax, fromY + dl*deltay);} else { this.moveTo(fromX + dl*deltax, fromY + dl*deltay); } }this.stroke();};
Demo of calling in HTML:
<!DOCTYPE html>