PK creative Spring Festival, I am participating in the “Spring Festival creative submission contest”, please see: Spring Festival creative submission Contest

The Spring Festival, I wish everyone a prosperous year of the Tiger, can grab the train ticket home

Material preparation

Background image of bullet train ticket

Interface implementation

According to the requirement, we need to position the text to the specified position of the picture. It is natural for us to use absolute for positioning, but if we do not specify the relative position of its parent element, The top, left and other attributes in absolute element will be positioned relative to body, so the positioning will be confused at different resolutions. The diagram below:

Random interesting information

The number and price information is pre-defined in the array, each time the information is entered, a random one is pulled out and displayed on the page, and then we need a random function to generate the desired array subscripts. The code is as follows:

getRandomInt: function(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; // no maximum, no minimum}Copy the code
Code interpretation
  1. Math.ceil()The function returns the smallest integer greater than or equal to a given number
  2. Math.floor()Returns the largest integer less than or equal to a given number
  3. Math.random()The function returns a floating point number, pseudorandom number in range[0, 1)
  4. Input parameters are first processed, with the minimum guaranteed to be an integer greater than or equal to itself and the maximum guaranteed to be an integer less than or equal to itself.Math.random() * (max - min)Ensure that generate[0, (max - min))Interval random numberMath.floor()To return a maximum integer less than or equal to itself, thus generating[0, (max - min))Is a random integer, finally plus the minimum number, can be guaranteed to generate[min, max)Random integer of

Save as a picture

Finally, we need to save the generated effect as a picture, here I use the plug-in html2Canvas, this plug-in is also very simple to use, the code is as follows:

HandleExportData: function() {html2Canvas (document.querySelector('.show-info'), {scale: 2, // True, // (prendered) allowTaint: false, // Support cross-domain (prendered) onRendered: function(canvas){ const exportImgLinkEle = document.querySelector('#exportImgLink'); exportImgLinkEle.href = canvas.toDataURL('image/png'); exportImgLinkEle.click(); // Perform the <a> element download}})}Copy the code
Pay attention to
  1. The image introduced by the corresponding node must behttpLink form if it is a relative path picture will not be shown
  2. Cross-domain configuration must be addeduseCORS: trueallowTaint: falseOtherwise, the picture will not be displayed

The Demo address

Link directly to: output.jsbin.com/wuneyovuce