Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to break through the restriction of canvas grammar and make him support chained grammar

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how to break through the restrictions of canvas grammar to make him support chained grammar. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Let's first take a look at a normal canvas drawing syntax:

The code is as follows:

Ctx.arc (centerX,centerY,radius,0,PI*2,true)

Ctx.shadowColor = 'rgba (0pc0re0p0pr 0.5)'

Ctx.shadowBlur = "10"

Ctx.fill ()

Ctx.beginPath ()

Ctx.shadowColor = 'rgba (0pc0pc0p0p0p0p0)'

Ctx.moveTo (centerX-radius,centerY)

Ctx.lineTo (centerX-radius,centerY-50)

Ctx.lineTo (centerX+radius,centerY-50)

Ctx.lineTo (centerX+radius,centerY)

/ / ctx.lineTo (centerX-radius,centerY)

Ctx.fill ()

Ctx.beginPath ()

Ctx.fillStyle = 'rgba (255pc0pl 0pl)'

Ctx.arc (centerX,centerY-50,radius,0,PI*2,true)

Ctx.fill ()

There are two things that upset me about the native grammar of canvas: 1 is that every sentence is preceded by a ctx (that is, the context2d object of canvas), and 2 is that each function or attribute occupies a line, wasting space.

I appreciate the chained syntax of jQuery, such as:

The code is as follows:

$('# div1') .show (300) .html (p) .delay (3000) .slideUp (300) .remove ()

So, I also want to use this syntax for canvas drawing:

The code is as follows:

Ctx.moveTo (500). LineTo (500500). StrokeStyle ('# f00'). Stroke ()

One way to do this is to simulate a context2d object that supports all native context2d methods but also supports chaining.

However, you can't have too much code, and no one likes to use it if you have too much code.

Here is the complete code snippet, which I named XtendCanvas (which begins with X again):

The code is as follows:

/ / Let canvas support chained syntax, from Ten year Lamp

~ function () {var pro = ['save','restore',' scale', 'rotate',' translate', 'transform',' createLinearGradient', 'createRadialGradient',' getLineDash', 'clearRect',' beginPath', 'closePath',' moveTo', 'lineTo',' quadraticCurveTo', 'bezierCurveTo',' arcTo', 'rect',' arc', 'fill',' stroke', 'clip',' isPointInPath', 'measureText' 'clearShadow', 'fillText',' strokeText', 'strokeRect',' drawImage', 'drawImageFromRect',' putImageData', 'createPattern',' createImageData', 'getImageData',' lineWidth','strokeStyle','globalAlpha','fillStyle','font','shadowOffsetX','shadowOffsetY','shadowBlur','shadowColor','lineCap','lineJoin','miterLimit']

Function XtendCanvas (canvas) {

Var ctx = canvas.getContext ('2d')

Fn = function () {}

FnP = fn.prototype

For (var j = 0) [0]; pscape pro [jacks +]) {

Fn.prototype [p] = function (p) {

Return function () {

Var args = Array.prototype.slice.call (arguments)

/ / console.log (args)

If (typeof ctx [p] = = 'function') {

Ctx.apply (ctx,args)

} else {

Ctx [p] = args+''

}

Return fnP

}

} (p)

}

Return new fn

}

Window.XtendCanvas = XtendCanvas

} ()

The method is simple. Pass him a canvas object and he will return an object similar to context2d. You can use it like a normal context2d, but the difference is that he supports chained syntax:

The code is as follows:

Var cvs = document.getElementById ('cvs')

Var ctx = XtendCanvas (cvs)

Ctx.moveTo (500). LineTo (500500). StrokeStyle ('# f00'). Stroke ()

In this way, you can put all your operations in one sentence, or you can interrupt at any time, do something else, and then move on.

This code is not an enhancement to canvas, but simply allows him to support chained syntax. But the advantage is that there is little code, which can be embedded in any JS library. Here, I hope to get a "recommendation" from you.

There must be something worth improving in the code, and you can improve it on your own. But-- the draught never forgets the well digger. I hope everyone will remember me. The most important thing is to think, right? Here are the ideas:

As you can see, the longest part of the code is the array pro that holds the method name, while the core code is very short. Why would I build such an array?

I also wanted to inherit all the native methods directly from CanvasRenderingContext2D, but the results were inconsistent when I iterated through the CanvasRenderingContext2D under each browser. If I inherit them directly, you will get an error when you want to execute them in firefox using the methods in chrome.

So I just extracted the general, undisputed methods and attribute names from CanvasRenderingContext2D. I have no choice but to build a fixed array-- you can decide to add your methods to it.

The methods and attributes are extracted, and then the native methods are added to my new object. I built an empty function called fn and put my method.

Because these elements in the array have both functions and attributes, I determine in the loop whether it is a function, and if it is a function, execute it with an argument; if it is not a function-- then it must be an attribute, and assign the parameter to this property.

In this way, when you set the canvas property, you don't have to break the chain, just pass the attribute value as a parameter, for example:

The code is as follows:

Ctx.strokeStyle ('# f00')

Finally, the key point is to return fn, which is learned from jQuery and is the key to supporting chained syntax.

Anonymous functions, closures, prototypes, and the strange for loops I talked about in previous articles are used in this paragraph.

It seems quite simple to say, but I have really thought about it for a long time and hope it will be useful to all of you.

In the process of writing code, I found that chrome's approach is very good, he has a string of functions starting with set, such as setStrokeColor,setLineCap and other functions, pass parameters to them, you can replace the corresponding attributes such as strokeStyle and lineCap, that is to say, his canvas is full of functions and no attributes, so I do not have to judge whether it is a function or an attribute. But there is no such thing in firefox, so I can only use the previous idea.

Let me also release that string of set functions:

The code is as follows:

Var bak = ['setTransform','setAlpha',' setCompositeOperation', 'setLineWidth',' setLineCap', 'setLineJoin',' setMiterLimit', 'setLineDash','setShadow','setStrokeColor','setFillColor']

Their usefulness is easy to see. You can also choose to add some to the pro array in the previous code.

Thank you for reading! This is the end of the article on "how to break the restriction of canvas grammar to make him support chained grammar". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report