waving flag waving flag - html5-canvas

<script type="text/javascript">
canvas.onmouseover = function onMouseover(e) {
waveFlag( flag, 20, 10, 150, 200, -0.1 );
}
canvas.onmouseout = function onMouseover(e) {
}
</script>
Above code is when the mouse move to the flag the flag will waving, how can i stop waving the flag when mouse out???

Just stop the setInterval from firing and the function will stop
<script type="text/javascript">
var timer = null;
function waveFlag( canvas, wavelength, amplitude, period, shading, squeeze ) {
if (!squeeze) squeeze = 0;
if (!shading) shading = 100;
if (!period) period = 200;
if (!amplitude) amplitude = 10;
if (!wavelength) wavelength = canvas.width/10;
var fps = 30;
var ctx = canvas.getContext('2d');
var w = canvas.width, h = canvas.height;
var od = ctx.getImageData(0,0,w,h).data;
// var ct = 0, st=new Date;
return setInterval(function(){
var id = ctx.getImageData(0,0,w,h);
var d = id.data;
var now = (new Date)/period;
for (var y=0;y<h;++y){
var lastO=0,shade=0;
var sq = (y-h/2)*squeeze;
for (var x=0;x<w;++x){
var px = (y*w + x)*4;
var pct = x/w;
var o = Math.sin(x/wavelength-now)*amplitude*pct;
var y2 = y + (o+sq*pct)<<0;
var opx = (y2*w + x)*4;
shade = (o-lastO)*shading;
d[px ] = od[opx ]+shade;
d[px+1] = od[opx+1]+shade;
d[px+2] = od[opx+2]+shade;
d[px+3] = od[opx+3];
lastO = o;
}
}
ctx.putImageData(id,0,0);
// if ((++ct)%100 == 0) console.log( 1000 * ct / (new Date - st));
},1000/fps);
}
var canvas = document.getElementById("flag");
canvas.onmouseover = function onMouseover(e) {
timer = waveFlag( flag, 20, 10, 150, 200, -0.1 );
}
canvas.onmouseout = function onMouseover(e) {
window.clearInterval(timer);
timer = null;
}
</script>

Related

Remove vertical label axis of Multiple-Value-Axes amchart

I am okay all the line types under graph but I don't need their vertical represents
morever I have only one axis and yaxis values in my chart but multiple lines.
How can I customize this amchart sample or find any suitable chart for my need?
Practically every component in the chart has a disabled property that you can use to hide or reveal. To get rid of the line and labels, simply set the disabled property to true to remove them, similar to how the grid was disabled:
valueAxis.renderer.line.disabled = true; //disables axis line
valueAxis.renderer.labels.template.disabled = true; //disables labels
valueAxis.renderer.grid.template.disabled = true; //disables grid
Demo:
// Create chart instance
var chart = am4core.create("chartdiv", am4charts.XYChart);
// Increase contrast by taking evey second color
chart.colors.step = 2;
// Add data
chart.data = generateChartData();
// Create axes
var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
// Create series
function createAxisAndSeries(field, name, bullet) {
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
var series = chart.series.push(new am4charts.LineSeries());
series.dataFields.valueY = field;
series.dataFields.dateX = "date";
series.strokeWidth = 2;
series.yAxis = valueAxis;
series.name = name;
series.tooltipText = "{name}: [bold]{valueY}[/]";
series.tensionX = 0.8;
var interfaceColors = new am4core.InterfaceColorSet();
switch(bullet) {
case "triangle":
var bullet = series.bullets.push(new am4charts.Bullet());
bullet.width = 12;
bullet.height = 12;
bullet.horizontalCenter = "middle";
bullet.verticalCenter = "middle";
var triangle = bullet.createChild(am4core.Triangle);
triangle.stroke = interfaceColors.getFor("background");
triangle.strokeWidth = 2;
triangle.direction = "top";
triangle.width = 12;
triangle.height = 12;
break;
case "rectangle":
var bullet = series.bullets.push(new am4charts.Bullet());
bullet.width = 10;
bullet.height = 10;
bullet.horizontalCenter = "middle";
bullet.verticalCenter = "middle";
var rectangle = bullet.createChild(am4core.Rectangle);
rectangle.stroke = interfaceColors.getFor("background");
rectangle.strokeWidth = 2;
rectangle.width = 10;
rectangle.height = 10;
break;
default:
var bullet = series.bullets.push(new am4charts.CircleBullet());
bullet.circle.stroke = interfaceColors.getFor("background");
bullet.circle.strokeWidth = 2;
break;
}
valueAxis.renderer.line.disabled = true;
valueAxis.renderer.labels.template.disabled = true;
valueAxis.renderer.grid.template.disabled = true;
}
createAxisAndSeries("visits", "Visits", "circle");
createAxisAndSeries("views", "Views", "triangle");
createAxisAndSeries("hits", "Hits", "rectangle");
// Add legend
chart.legend = new am4charts.Legend();
// Add cursor
chart.cursor = new am4charts.XYCursor();
// generate some random data, quite different range
function generateChartData() {
var chartData = [];
var firstDate = new Date();
firstDate.setDate(firstDate.getDate() - 100);
firstDate.setHours(0, 0, 0, 0);
var visits = 1600;
var hits = 2900;
var views = 8700;
for (var i = 0; i < 15; i++) {
// we create date objects here. In your data, you can have date strings
// and then set format of your dates using chart.dataDateFormat property,
// however when possible, use date objects, as this will speed up chart rendering.
var newDate = new Date(firstDate);
newDate.setDate(newDate.getDate() + i);
visits += Math.round((Math.random()<0.5?1:-1)*Math.random()*10);
hits += Math.round((Math.random()<0.5?1:-1)*Math.random()*10);
views += Math.round((Math.random()<0.5?1:-1)*Math.random()*10);
chartData.push({
date: newDate,
visits: visits,
hits: hits,
views: views
});
}
return chartData;
}
#chartdiv {
width: 100%;
height: 500px;
}
<script src="https://www.amcharts.com/lib/4/core.js"></script>
<script src="https://www.amcharts.com/lib/4/charts.js"></script>
<div id="chartdiv"></div>
multiple-value-axes remove 3rd axis from chart.
Only two axis will show.

Three.js + Tween.js tweening vertices of multiple objects

I am using three.js to create multiple BoxGeometries and tween.js to animate all vertices of the geometry.
At first all cubes should randomly distort untill i call stopTweens(). Then all vertices should go back to their default posiiton.
My problem is, that only the last cube gets reseted visually. The others are also tweened, but it seems like verticesNeedUpdate is not set to true and so nothing is happening on the screen.
Here is my Code:
var scene_03_TweenArr = [];
Function to create Cubes:
function createCubes(){
for (i = 0; i < 10; i++) {
var CubeGeometry = new THREE.BoxGeometry( 4, 4, 4, 5, 5, 5 );
var CubeMaterial = new THREE.MeshPhongMaterial( {color: 0xffffff} );
var cube = new THREE.Mesh( CubeGeometry, CubeMaterial );
scene_03.add( cube );
cube.position.x = -40+5*i;
tt_animate_vertices(cube);
}
}
Function to animate Cubes randomly:
function tt_animate_vertices(object) {
for( j = 0; j < object.geometry.vertices.length; j++ ){
var previousX = object.geometry.vertices[j].x;
var previousY = object.geometry.vertices[j].y;
var previousZ = object.geometry.vertices[j].z;
var tween = new TWEEN.Tween(object.geometry.vertices[j]);
tween.to({ x: (0.25*Math.random()+1)*previousX, y: (0.25*Math.random()+1)*previousY, z: (0.25*Math.random()+1)*previousZ }, 5000 + Math.random()*5000);
var tween2 = new TWEEN.Tween(object.geometry.vertices[j]);
tween2.to({ x: previousX, y: previousY, z: previousZ }, 5000 + Math.random()*5000);
tween.onUpdate(function(){
object.geometry.verticesNeedUpdate = true;
});
tween2.onUpdate(function(){
object.geometry.verticesNeedUpdate = true;
});
tween.chain(tween2);
tween2.chain(tween);
tween.start();
var verticeTween = [object, tween, tween2, j, previousX, previousY, previousZ ];
scene_03_TweenArr.push(verticeTween);
}
}
Function to stop tweens and reset cubevertices to default:
function stopTweens(){
for (let k = 0; k < scene_03_TweenArr.length; k++) {
scene_03_TweenArr[k][1].stop();
scene_03_TweenArr[k][2].stop();
var object = scene_03_TweenArr[k][0];
var index = scene_03_TweenArr[k][3];
var prevX = scene_03_TweenArr[k][4];
var prevY = scene_03_TweenArr[k][5];
var prevZ = scene_03_TweenArr[k][6];
var tween = new TWEEN.Tween(object.geometry.vertices[index]);
tween.to({x: prevX, y: prevY, z: prevZ }, 300)
tween.onUpdate(function(){
object.geometry.verticesNeedUpdate = true;
});
tween.start();
object.geometry.verticesNeedUpdate = true;
}
}
Here I managed to make it run in JSFiddle with the same behaviour:
http://jsfiddle.net/gfhyvou3/25/
From my experience, it's better to use let keyword inside loops, when you work with arrays.
function stopTweens(){
for (let k = 0; k < scene_03_TweenArr.length; k++) {
scene_03_TweenArr[k][1].stop();
scene_03_TweenArr[k][2].stop();
let object = scene_03_TweenArr[k][0];
let index = scene_03_TweenArr[k][3];
let prevX = scene_03_TweenArr[k][4];
let prevY = scene_03_TweenArr[k][5];
let prevZ = scene_03_TweenArr[k][6];
var tween = new TWEEN.Tween(object.geometry.vertices[index]);
tween.to({x: prevX, y: prevY, z: prevZ }, 300)
tween.onUpdate(function(){
object.geometry.verticesNeedUpdate = true;
});
tween.start();
object.geometry.verticesNeedUpdate = true;
}
}

Transparency update via slider doesn't work in Firefox Mobile

I've created a slider to change the transparency of a cube created with three.js. The code works well with all browsers in the desktop. However, in the Android System (version 5.0), the Firefox browser (version of May 8) is unable to update the transparency.
Here is the web page with the applet: http://www.im-uff.mat.br/tmp/how/simple-11.html
The code is here:
<!-- saved from url=(0016)http://localhost -->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Orthogonal Projections 1</title>
<!-- JavaScript Libraries -->
<script src="threejs.r91/build/three.js"></script>
<script src="threejs.r91/examples/js/controls/TrackballControls.js"></script>
<script src="threejs.r91/examples/js/loaders/DDSLoader.js"></script>
<script src="threejs.r91/examples/js/loaders/MTLLoader.js"></script>
<script src="threejs.r91/examples/js/loaders/OBJLoader.js"></script>
<!-- ThreeJS Code -->
<script type="text/javascript">
window.addEventListener('load',
function()
{
document.getElementById('tr').style.visibility = "visible";
});
var transparency_value = 0;
function MakeQuadrilateral(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4)
{
var geo = new THREE.Geometry();
// generate vertices
geo.vertices.push( new THREE.Vector3(x1,y1,z1));
geo.vertices.push( new THREE.Vector3(x2,y2,z2));
geo.vertices.push( new THREE.Vector3(x3,y3,z3));
geo.vertices.push( new THREE.Vector3(x4,y4,z4));
geo.faces.push( new THREE.Face3(0,1,2));
geo.faces.push( new THREE.Face3(0,2,3));
// Return the geometry object
return geo;
}
// Adds text to the screen
function makeSpriteText(text)
{
var canvas = document.createElement('canvas');
var size = 256; // CHANGED
canvas.width = size;
canvas.height = size;
var context = canvas.getContext('2d');
context.fillStyle = '#ffffff'; // CHANGED
context.textAlign = 'center';
context.font = '48px Times';
context.fillText(text, size / 2, size / 2);
var amap = new THREE.Texture(canvas);
amap.needsUpdate = true;
var mat = new THREE.SpriteMaterial({
map: amap,
transparent: false,
useScreenCoordinates: false,
color: 0x0000ff // CHANGED
});
var sp = new THREE.Sprite(mat);
return(sp);
}
// Check capabilities, and start if sufficient
var hasWebGl = (function() {try {return !! window.WebGLRenderingContext &&
!! document.createElement('canvas').getContext('experimental-webgl');}
catch(e){return false;}})();
var hasCanvas = !! window.CanvasRenderingContext2D; // Converts value to boolean
var hasVibration = navigator.vibrate;
window.onresize = function(event)
{
if (loaded == true)
{
loaded = false;
context0.controls = new THREE.TrackballControls(context0.camera, context0.renderer.domElement);
context0.controls.target.set(0, 0, 0);
context0.controls.noZoom = false;
context0.controls.noPan = true;
context0.controls.rotateSpeed = 1.2;
context0.controls.dynamicDampingFactor = 0.2;
context0.controls.staticMoving = false;
}
}
if (hasCanvas)
{
document.addEventListener( "DOMContentLoaded", init, false);
} // End of if()
function init()
{
// Setup idiom
document.getElementById("msgwebglcontext0").innerHTML = "<br>";
/* spawns the objects, scenes, cameras, renderers etc. */
context0 = {color: 0xccff33, name: "0", width: 440, height: 440, factor: 30, arrowLength: 25};
// set the scene
if (hasWebGl)
{
context0.renderer = new THREE.WebGLRenderer({alpha: true, antialias: true });
}
else
{
context0.renderer = new THREE.CanvasRenderer({alpha: true, antialias: true });
}
context0.renderer.setSize(context0.width, context0.height);
// Add the renderer to the document.
// This should be called before THREE.TrackballControls().
document.getElementById("webglcontext0").appendChild(context0.renderer.domElement);
context0.scene = new THREE.Scene();
context0.camera = new THREE.PerspectiveCamera(20, context0.height/context0.width, 2, 10000); // 20: small values cause z-buffer fighting
context0.camera.position.z = 70;
context0.camera.position.x = 70;
context0.camera.position.y = 70;
context0.scene.add(context0.camera);
context0.controls = new THREE.TrackballControls(context0.camera, context0.renderer.domElement);
context0.controls.target.set(0, 0, 0);
context0.controls.noZoom = false;
context0.controls.noPan = true;
// Model
var onProgress = function ( xhr ) {
if ( xhr.lengthComputable ) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log( Math.round(percentComplete, 2) + '% downloaded' );
}
};
var onError = function ( xhr ) { };
THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() );
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath( 'obj/' );
mtlLoader.load( 'platonic-cube.obj.mtl', function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.setPath( 'obj/' );
objLoader.load( 'platonic-cube.obj', function ( object )
{
object.traverse(function (child)
{
if (child instanceof THREE.Mesh)
{
// Polyhedra
child.name = "pdp-faces";
context0.scene.add(child);
var geometry = new THREE.Geometry().fromBufferGeometry( child.geometry );
console.log('From loaded OBJ: ' + geometry.vertices.length);
if ( Array.isArray( child.material ) )
{
var n = child.material.length;
for (i = 0; i < n; i++)
{
child.material[i].transparent = true;
child.material[i].opacity = (1 - transparency_value/100.0);
};
}
else
{
child.material.transparent = true;
child.material.opacity = (1 - transparency_value/100.0);
}
// Edges
var edges = new THREE.LineSegments(new THREE.EdgesGeometry(child.geometry), new THREE.LineBasicMaterial( {color: 0x000000}) );
edges.name = "pdp-edges";
context0.scene.add(edges);
// Vertices
var geometry = new THREE.Geometry().fromBufferGeometry( edges.geometry );
console.log('Geometry vertices length: ' + geometry.vertices.length);
var vertices = [];
var isNew;
var tolerance = 0.0000001;
if (geometry.vertices.length > 0)
{
vertices.push(new THREE.Vector3(geometry.vertices[0].x, geometry.vertices[0].y, geometry.vertices[0].z));
}
for (i = 1; i < geometry.vertices.length; i++)
{
l = vertices.length;
isNew = true;
for (j = 0; j < l; j++)
{
var d = geometry.vertices[i].distanceTo(vertices[j]);
if (d < tolerance)
{
isNew = false;
}
}
if (isNew == true)
{
vertices.push(new THREE.Vector3(geometry.vertices[i].x, geometry.vertices[i].y, geometry.vertices[i].z));
}
}
/*
alert('Unique vertices: ' + vertices.length);
for (i = 0; i < vertices.length; i++)
{
alert(vertices[i].x);
}
*/
// https://github.com/stemkoski/stemkoski.github.com/blob/master/Three.js/Polyhedra.html
// https://stemkoski.github.io/Three.js/Polyhedra.html
// Fit screen
child.geometry.computeBoundingSphere();
var fov = context0.camera.fov * ( Math.PI / 180 );
var objectSize = child.geometry.boundingSphere.radius;
var distance = 0.7*Math.abs( objectSize / Math.sin( fov / 2 ) );
context0.camera.position.z = 2.5*distance;
context0.camera.position.x = 2.5*distance;
context0.camera.position.y = 2.5*distance;
// PLANE PROJECTIONS
var geometry_xy = new THREE.Geometry().fromBufferGeometry( edges.geometry );
var geometry_xz = new THREE.Geometry().fromBufferGeometry( edges.geometry );
var geometry_yz = new THREE.Geometry().fromBufferGeometry( edges.geometry );
geometry_xy.dynamic = true;
geometry_xz.dynamic = true;
geometry_yz.dynamic = true;
for (i = 0; i < geometry_xy.vertices.length; i++)
{
var xOld = geometry_xy.vertices[i].x;
var yOld = geometry_xy.vertices[i].y;
var zOld = geometry_xy.vertices[i].z;
geometry_xy.vertices[i].set(xOld, yOld, -distance/3);
geometry_xz.vertices[i].set(xOld, -distance/3, zOld);
geometry_yz.vertices[i].set(-distance/3, yOld, zOld);
// console.log(geometry_xy.vertices[i].x + ' ' + geometry_xy.vertices[i].y + ' ' + geometry_xy.vertices[i].z);
}
geometry_xy.verticesNeedUpdate = true;
geometry_xz.verticesNeedUpdate = true;
geometry_yz.verticesNeedUpdate = true;
var edges_xy = new THREE.LineSegments(geometry_xy, new THREE.LineBasicMaterial( {color: 0x000000}) );
var edges_xz = new THREE.LineSegments(geometry_xz, new THREE.LineBasicMaterial( {color: 0x000000}) );
var edges_yz = new THREE.LineSegments(geometry_yz, new THREE.LineBasicMaterial( {color: 0x000000}) );
edges_xy.name = "pdp-edges-xy";
edges_xz.name = "pdp-edges-xz";
edges_yz.name = "pdp-edges-yz";
context0.scene.add(edges_xy);
context0.scene.add(edges_xz);
context0.scene.add(edges_yz);
// VERTICES
var vertexGeometry = new THREE.SphereGeometry(child.geometry.boundingSphere.radius/35.0, 12, 6 );
var vertexMaterial = new THREE.MeshBasicMaterial( { color: 0x000000 } );
var vertexSingleMesh = new THREE.Mesh( vertexGeometry );
var vertexAmalgam = new THREE.Geometry();
for (var i = 0; i < vertices.length; i++)
{
var vMesh = vertexSingleMesh.clone();
vMesh.position.set(vertices[i].x, vertices[i].y, vertices[i].z);
THREE.GeometryUtils.merge( vertexAmalgam, vMesh );
}
var vertexMesh = new THREE.Mesh( vertexAmalgam, vertexMaterial );
vertexMesh.name = "pdp-vertices";
context0.scene.add(vertexMesh);
context0.scene.getObjectByName("pdp-vertices").visible = false;
// PLANES
var d = distance/3;
var xyGeometry = MakeQuadrilateral( d, -d, -d,
d, d, -d,
-d, d, -d,
-d, -d, -d);
var xyPlane = new THREE.Mesh(xyGeometry, new THREE.MeshBasicMaterial({color: 0x090909, side: THREE.DoubleSide, opacity: 0.2, transparent: true }));
xyPlane.name = "xyPlane";
context0.scene.add(xyPlane);
var d = distance/3;
var xzGeometry = MakeQuadrilateral( d, -d, d,
d, -d, -d,
-d, -d, -d,
-d, -d, d);
var xzPlane = new THREE.Mesh(xzGeometry, new THREE.MeshBasicMaterial({color: 0x090909, side: THREE.DoubleSide, opacity: 0.2, transparent: true }));
xzPlane.name = "xzPlane";
context0.scene.add(xzPlane);
var d = distance/3;
var yzGeometry = MakeQuadrilateral( -d, -d, d,
-d, -d, -d,
-d, d, -d,
-d, d, d);
var yzPlane = new THREE.Mesh(yzGeometry, new THREE.MeshBasicMaterial({color: 0x090909, side: THREE.DoubleSide, opacity: 0.2, transparent: true }));
yzPlane.name = "yzPlane";
context0.scene.add(yzPlane);
// AXES
var xVector = new THREE.ArrowHelper(new THREE.Vector3(1, 0, 0),
new THREE.Vector3(-d, -d, -d ),
2*d + 0.5*d, 0x0000ff, 0.2*d, 0.1*d);
xVector.name = "xVector";
xVector.line.visible = true;
xVector.cone.visible = true;
context0.scene.add( xVector );
var xLabel = makeSpriteText("y");
xLabel.name = "xLabel";
xLabel.position.set(d + 0.7*d, -d, -d);
xLabel.scale.set( d, d, d );
context0.scene.add(xLabel);
var yVector = new THREE.ArrowHelper(new THREE.Vector3(0, 1, 0),
new THREE.Vector3(-d, -d, -d),
2*d + 0.5*d, 0x0000ff, 0.2*d, 0.1*d);
yVector.name = "yVector";
yVector.line.visible = true;
yVector.cone.visible = true;
context0.scene.add(yVector );
var yLabel = makeSpriteText("z");
yLabel.name = "yLabel";
yLabel.position.set(-d, d + 0.6*d, -d);
yLabel.scale.set( 10, 10, 10 );
context0.scene.add(yLabel);
var zVector = new THREE.ArrowHelper(new THREE.Vector3(0, 0, 1),
new THREE.Vector3(-d, -d, -d),
2*d + 0.5*d, 0x0000ff, 0.2*d, 0.1*d);
zVector.name = "zVector";
zVector.line.visible = true;
zVector.cone.visible = true;
context0.scene.add(zVector );
var zLabel = makeSpriteText("x");
zLabel.name = "zLabel";
zLabel.position.set(-d, -d, d + 0.7*d);
zLabel.scale.set( 10, 10, 10 );
context0.scene.add(zLabel);
}
});
}, onProgress, onError );
});
// var ambLight = new THREE.AmbientLight(0x404040);
// context0.scene.add(ambLight);
context0.light = new THREE.DirectionalLight(0xffffff, 1);
context0.light.position = context0.camera.position;
context0.scene.add(context0.light);
// Run
context0.camera.updateProjectionMatrix();
render();
animate();
loaded = true;
} // End of init()
function animate()
{
/* One animation tick */
requestAnimationFrame(animate);
context0.controls.update();
render();
} // End of animate()
function render()
{
/* renders our little scene */
context0.renderer.render(context0.scene, context0.camera);
} // End of render()
</script>
</head>
<body> <!-- <body onload='disableScroll();'> -->
<center>
<table>
<tr>
<td>
<span id="webglcontext0" style="width:410px; height:50px; display: table-cell; text-align:center; vertical-align: middle; border-style: solid; border-width: 1px;"></span>
<div id="msgwebglcontext0" style="text-align:center; display: table; margin-left: -3px;">
<span style="width:743px; height:30px; display: table-cell; text-align:justify; padding:10px; vertical-align: middle; border-style: solid; border-width: 1px;">
Por favor, espere o navegador carregar a página. Caso
isto já tenha acontecido e o applet abaixo não executou, isto significa que seu navegador parece não suportar WebGL ou esta opção não está habilitada.
Em caso de dúvidas, entre em contato conosco pelo e-mail:
conteudosdigitais#im.uff.br.
</span>
</div>
</td>
<td align="center">
<input
name="transparency_range"
id="tr"
type="range"
min="0" // default 0
max="100" // default 100
step="1" // default 1
value="0" // default min + (max-min)/2
oninput="updateTransparency(this.value)" onchange="updateTransparency(this.value)" ondrag="updateTransparency(this.value)"
style="visibility: hidden"
>
<br>
<span id="texto">0</span>
</td>
</tr>
</table>
</center>
<script type="text/javascript">
function updateTransparency(val)
{
transparency_value = val;
if ((loaded == true))
{
if ( Array.isArray( context0.scene.getObjectByName("pdp-faces").material ) )
{
var n = context0.scene.getObjectByName("pdp-faces").material.length;
for (i = 0; i < n; i++)
{
context0.scene.getObjectByName("pdp-faces").material[i].transparent = true;
context0.scene.getObjectByName("pdp-faces").material[i].opacity = (1 - transparency_value/100.0);
context0.renderer.render(context0.scene, context0.camera);
};
}
else
{
context0.scene.getObjectByName("pdp-faces").material.transparent = true;
context0.scene.getObjectByName("pdp-faces").material.opacity = (1 - transparency_value/100.0);
context0.renderer.render(context0.scene, context0.camera);
}
}
document.getElementById("texto").innerHTML = val;
}
</script>
</body>
</html>
Any hint about what is happening here?
Thanks in advance, Humberto.

THREE js : Simplify a mesh to optimize performance

I have a mesh (image 1) and a parallelepipede, I add the intersection result of this 2 objects in a scene and I move the parallelepipede along my mesh repeating the same process to "cut" my mesh and get an exploded view of my mesh (image 2).
Problem is that the process time is more than 2 mins... I have tryed to reduce the mesh with meshmixxer but it's not enough... Does someone has another idea ?
function FirstCut() {
var scene, camera, renderer, controls;
//stl loader from https://threejs.org/examples/webgl_loader_stl.html
// cf example https://stemkoski.github.io/Three.js/CSG.html
//with obj
init();
animate();
function init() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0xeeeeee);
camera = new THREE.PerspectiveCamera(75, 800 / 500, 1, 2000);
//camera.position.set(50, 500, 0);
camera.position.x = 50;
camera.position.y = 500;
camera.position.z = 0;
//var axeX = new THREE.Vector3(1, 0, 0);
//camera.rotateOnAxis(axeX, -1);
camera.lookAt(new THREE.Vector3(0, 500, 0));
controls = new THREE.OrbitControls(camera);
//les valeurs de min and max distance sont choisies pour que le filet ne disparaisse pas quand on le fait tourner
controls.minDistance = 0;
controls.maxDistance = 1000;
//scene
//var ambient = new THREE.AmbientLight(0x101030);
//scene.add(ambient);
//scene.add(new THREE.GridHelper(1000, 20));
//var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
//directionalLight.position.set(0, 1, 0);
//scene.add(directionalLight);
var widthH = parseInt(document.getElementById("wdthH").value) || 0; // H for Head
var widthT = parseInt(document.getElementById("wdthT").value) || 0; // T for tail
var height = parseInt(document.getElementById("hght").value) || 0; // flank
//création du pavé
var EmportePieceH = new THREE.BoxGeometry(300, 60, widthH);
var EmportePieceT = new THREE.BoxGeometry(300, 60, widthT);
var EmportePieceB = new THREE.BoxGeometry(height, 60, 520);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
// création du meshage et material
var EmportePieceMeshH = new THREE.Mesh(EmportePieceH, paveMaterial);
var EmportePieceMeshT = new THREE.Mesh(EmportePieceT, paveMaterial);
var paveMeshB = new THREE.Mesh(EmportePieceB, paveMaterial);
var zH = 247 - widthH / 2;
var zT = -247 + widthT / 2;
EmportePieceMeshH.position.set(0, 30, zH);
EmportePieceMeshT.position.set(0, 30, zT);
paveMeshB.position.set(-95 + height / 2, 30, 0);
var EmportePieceBSPH = new ThreeBSP(EmportePieceMeshH);
var EmportePieceBSPT = new ThreeBSP(EmportePieceMeshT);
var paveBSPB = new ThreeBSP(paveMeshB);
//scene.add(EmportePieceMeshH);
//scene.add(EmportePieceMeshT);
//scene.add(paveMeshB);
// texture
var manager = new THREE.LoadingManager();
manager.onProgress = function (item, loaded, total) {
console.log(item, loaded, total);
};
var texture = new THREE.Texture();
var onProgress = function (xhr) {
if (xhr.lengthComputable) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log(Math.round(percentComplete, 2) + '% downloaded');
}
};
var onError = function (xhr) {
};
var loader = new THREE.ImageLoader(manager);
loader.load('/Scan/filet_1kg500-reposition-reduit_material_0.jpg', function (image) {
texture.image = image;
texture.needsUpdate = true;
});
var width = parseInt(document.getElementById("wdth").value) || 0;
//création du pavé
var paveGeom = new THREE.BoxGeometry(250, 250, width);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
// création du meshage parallélépipède avec material
var paveMesh = new THREE.Mesh(paveGeom, paveMaterial);
var z0 = -247 + widthH;
paveMesh.position.set(0, 0, z0);
var paveBSP = new ThreeBSP(paveMesh);
//scene.add(paveMesh);
//tableau des volumes
var tabVolumes = new Array();
// model
var loader = new THREE.OBJLoader(manager);
loader.load('/Scan/filet_1kg500-reposition-reduit.obj', function (object) {
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material.map = texture;
var geo = new THREE.Geometry().fromBufferGeometry(child.geometry);
var filetMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true });
var filetMesh = new THREE.Mesh(geo, filetMaterial);
//scene.add(filetMesh);
var newBSPH, newBSPT, newBSPB, newBSP2, newBSP1, filletBSP
var filetBSP = new ThreeBSP(filetMesh);
newBSPH = filetBSP.intersect(EmportePieceBSPH);
newBSPT = filetBSP.intersect(EmportePieceBSPT);
newBSPB = filetBSP.intersect(paveBSPB);
newBSP2 = filetBSP.subtract(EmportePieceBSPH);
newBSP1 = newBSP2.subtract(paveBSPB);
filletBSP = newBSP1.subtract(EmportePieceBSPT);
////////////////////subtract//////////////////////////////
var newFilet = new THREE.Geometry();
newFilet = filletBSP.toGeometry();
var newFilletMesh = new THREE.Mesh(newFilet, new THREE.MeshBasicMaterial({ map: texture }));
newFilletMesh.position.set(0, 0, 0);
///////////////////////////////////création morceaux découpés///////////////////////////////////////////
var HeadFillet = new THREE.Geometry();
var TailFillet = new THREE.Geometry();
var degraissageFillet = new THREE.Geometry();
HeadFillet = newBSPH.toGeometry();
TailFillet = newBSPT.toGeometry();
degraissageFillet = newBSPB.toGeometry();
/////////////////////////////////calcul des volumes des 1ers morceaux/////////////////////////////////////////
if (widthH != 0) {
tabVolumes[0] = calculateVolume2(HeadFillet);
} else { tabVolumes[0] = 0;}
if (widthT != 0) {
//alert(tabVolumes[0]);
tabVolumes[1] = calculateVolume2(TailFillet);
} else { tabVolumes[1] = 0; }
if (height != 0) {
tabVolumes[2] = calculateVolume2(degraissageFillet);
} else { tabVolumes[2] = 0; }
var ind = 3;
var HeadFilletMesh = new THREE.Mesh(HeadFillet, new THREE.MeshBasicMaterial({ map: texture }));
var TailFilletMesh = new THREE.Mesh(TailFillet, new THREE.MeshBasicMaterial({ map: texture }));
var degraissageFilletMesh = new THREE.Mesh(degraissageFillet, new THREE.MeshBasicMaterial({ map: texture }));
HeadFilletMesh.position.set(0, 0, 20);
degraissageFilletMesh.position.set(-20, 0, 0);
TailFilletMesh.position.set(0, 0, -20);
scene.add(HeadFilletMesh);
scene.add(TailFilletMesh);
scene.add(degraissageFilletMesh);
//scene.add(newFilletMesh);
var cloneHeadFilletMesh = HeadFilletMesh.clone();
var cloneTailFilletMesh = TailFilletMesh.clone();
var clonedegraissageFilletMesh = degraissageFilletMesh.clone();
var mesh_decoupe = new THREE.Object3D;
mesh_decoupe.add(cloneHeadFilletMesh);
mesh_decoupe.add(cloneTailFilletMesh);
mesh_decoupe.add(clonedegraissageFilletMesh);
if (width != 0) {
var paveGeom = new THREE.BoxGeometry(300, 300, width);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
var fillet2BSP = new ThreeBSP(newFilletMesh);
var intersectionPave = new THREE.Geometry();
intersectionPave = fillet2BSP.intersect(paveBSP);
var geometryPave = new THREE.Geometry();
geometryPave = intersectionPave.toGeometry();
var newMesh = new THREE.Mesh(geometryPave, new THREE.MeshBasicMaterial({ map: texture }));
//alert(geometryPave.faces.length);
while (geometryPave.faces.length != 0) {
var z = paveMesh.position.z + width + 5;
paveMesh.position.set(0, 0, z);
paveBSP = new ThreeBSP(paveMesh);
//scene.add(paveMesh);
fillet2BSP = new ThreeBSP(newFilletMesh);
intersectionPave = filletBSP.intersect(paveBSP);
geometryPave = intersectionPave.toGeometry();
tabVolumes[ind] = calculateVolume2(geometryPave);
ind = ind + 1;
var newMesh = new THREE.Mesh(geometryPave, new THREE.MeshBasicMaterial({ map: texture }));
newMesh.position.set(0, 0, newMesh.position.z);
scene.add(newMesh);
var meshSave = newMesh.clone();
mesh_decoupe.add(meshSave);
}
document.body.style.cursor = '';
} else {
scene.add(newFilletMesh);
document.body.style.cursor = '';
tabVolumes[3] = 0;
tabVolumes[4] = calculateVolume2(newFilet);
}
// }
//}
//else {
// scene.add(newFilletMesh);
// tabVolumes[ind] = calculateVolume2(newFilet);
//}
//alert(calculateVolume2(newBSP.toGeometry()));
//afficher les volumes dans la textarea
var txtVolume = document.getElementById("txtVolume");
txtVolume.value = tabVolumes.join("\n");
//var exporter = new THREE.OBJExporter();
//var result = exporter.parse(mesh_decoupe);
//var blob = new Blob([result], { type: 'text/plain' });
//saveAs(blob, 'dechets.obj');
}
});
//scene.add(object);
}, onProgress, onError);
renderer = new THREE.WebGLRenderer();
renderer.setSize(800, 500, false);
document.getElementById('canvas3D').innerHTML = "";
document.getElementById('canvas3D').appendChild(renderer.domElement);
}
function animate() {
requestAnimationFrame(animate);
camin();
renderer.render(scene, camera);
}
function camin() {
camera.position.y -= .1;
}
function volumeOfT(p1, p2, p3) {
var v321 = p3.x * p2.y * p1.z;
var v231 = p2.x * p3.y * p1.z;
var v312 = p3.x * p1.y * p2.z;
var v132 = p1.x * p3.y * p2.z;
var v213 = p2.x * p1.y * p3.z;
var v123 = p1.x * p2.y * p3.z;
return (-v321 + v231 + v312 - v132 - v213 + v123) / 6.0;
}
function calculateVolume2(object) {
var volumes = 0.0;
for (var i = 0; i < object.faces.length; i++) {
var Pi = object.faces[i].a;
var Qi = object.faces[i].b;
var Ri = object.faces[i].c;
//alert (Pi);
var P = new THREE.Vector3(object.vertices[Pi].x, object.vertices[Pi].y, object.vertices[Pi].z);
//alert(object.vertices[Pi].x);
var Q = new THREE.Vector3(object.vertices[Qi].x, object.vertices[Qi].y, object.vertices[Qi].z);
var R = new THREE.Vector3(object.vertices[Ri].x, object.vertices[Ri].y, object.vertices[Ri].z);
volumes += volumeOfT(P, Q, R);
}
return Math.abs(volumes);
}
}
function FirstCut() {
var scene, camera, renderer, controls;
//stl loader from https://threejs.org/examples/webgl_loader_stl.html
// cf example https://stemkoski.github.io/Three.js/CSG.html
//with obj
init();
animate();
function init() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0xeeeeee);
camera = new THREE.PerspectiveCamera(75, 800 / 500, 1, 2000);
//camera.position.set(50, 500, 0);
camera.position.x = 50;
camera.position.y = 500;
camera.position.z = 0;
//var axeX = new THREE.Vector3(1, 0, 0);
//camera.rotateOnAxis(axeX, -1);
camera.lookAt(new THREE.Vector3(0, 500, 0));
controls = new THREE.OrbitControls(camera);
//les valeurs de min and max distance sont choisies pour que le filet ne disparaisse pas quand on le fait tourner
controls.minDistance = 0;
controls.maxDistance = 1000;
//scene
//var ambient = new THREE.AmbientLight(0x101030);
//scene.add(ambient);
//scene.add(new THREE.GridHelper(1000, 20));
//var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
//directionalLight.position.set(0, 1, 0);
//scene.add(directionalLight);
var widthH = parseInt(document.getElementById("wdthH").value) || 0; // H for Head
var widthT = parseInt(document.getElementById("wdthT").value) || 0; // T for tail
var height = parseInt(document.getElementById("hght").value) || 0; // flank
//création du pavé
var EmportePieceH = new THREE.BoxGeometry(300, 60, widthH);
var EmportePieceT = new THREE.BoxGeometry(300, 60, widthT);
var EmportePieceB = new THREE.BoxGeometry(height, 60, 520);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
// création du meshage et material
var EmportePieceMeshH = new THREE.Mesh(EmportePieceH, paveMaterial);
var EmportePieceMeshT = new THREE.Mesh(EmportePieceT, paveMaterial);
var paveMeshB = new THREE.Mesh(EmportePieceB, paveMaterial);
var zH = 247 - widthH / 2;
var zT = -247 + widthT / 2;
EmportePieceMeshH.position.set(0, 30, zH);
EmportePieceMeshT.position.set(0, 30, zT);
paveMeshB.position.set(-95 + height / 2, 30, 0);
var EmportePieceBSPH = new ThreeBSP(EmportePieceMeshH);
var EmportePieceBSPT = new ThreeBSP(EmportePieceMeshT);
var paveBSPB = new ThreeBSP(paveMeshB);
//scene.add(EmportePieceMeshH);
//scene.add(EmportePieceMeshT);
//scene.add(paveMeshB);
// texture
var manager = new THREE.LoadingManager();
manager.onProgress = function (item, loaded, total) {
console.log(item, loaded, total);
};
var texture = new THREE.Texture();
var onProgress = function (xhr) {
if (xhr.lengthComputable) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log(Math.round(percentComplete, 2) + '% downloaded');
}
};
var onError = function (xhr) {
};
var loader = new THREE.ImageLoader(manager);
loader.load('/Scan/filet_1kg500-reposition-reduit_material_0.jpg', function (image) {
texture.image = image;
texture.needsUpdate = true;
});
var width = parseInt(document.getElementById("wdth").value) || 0;
//création du pavé
var paveGeom = new THREE.BoxGeometry(250, 250, width);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
// création du meshage parallélépipède avec material
var paveMesh = new THREE.Mesh(paveGeom, paveMaterial);
var z0 = -247 + widthH;
paveMesh.position.set(0, 0, z0);
var paveBSP = new ThreeBSP(paveMesh);
//scene.add(paveMesh);
//tableau des volumes
var tabVolumes = new Array();
// model
var loader = new THREE.OBJLoader(manager);
loader.load('/Scan/filet_1kg500-reposition-reduit.obj', function (object) {
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material.map = texture;
var geo = new THREE.Geometry().fromBufferGeometry(child.geometry);
var filetMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true });
var filetMesh = new THREE.Mesh(geo, filetMaterial);
//scene.add(filetMesh);
var newBSPH, newBSPT, newBSPB, newBSP2, newBSP1, filletBSP
var filetBSP = new ThreeBSP(filetMesh);
newBSPH = filetBSP.intersect(EmportePieceBSPH);
newBSPT = filetBSP.intersect(EmportePieceBSPT);
newBSPB = filetBSP.intersect(paveBSPB);
newBSP2 = filetBSP.subtract(EmportePieceBSPH);
newBSP1 = newBSP2.subtract(paveBSPB);
filletBSP = newBSP1.subtract(EmportePieceBSPT);
////////////////////subtract//////////////////////////////
var newFilet = new THREE.Geometry();
newFilet = filletBSP.toGeometry();
var newFilletMesh = new THREE.Mesh(newFilet, new THREE.MeshBasicMaterial({ map: texture }));
newFilletMesh.position.set(0, 0, 0);
///////////////////////////////////création morceaux découpés///////////////////////////////////////////
var HeadFillet = new THREE.Geometry();
var TailFillet = new THREE.Geometry();
var degraissageFillet = new THREE.Geometry();
HeadFillet = newBSPH.toGeometry();
TailFillet = newBSPT.toGeometry();
degraissageFillet = newBSPB.toGeometry();
/////////////////////////////////calcul des volumes des 1ers morceaux/////////////////////////////////////////
if (widthH != 0) {
tabVolumes[0] = calculateVolume2(HeadFillet);
} else { tabVolumes[0] = 0;}
if (widthT != 0) {
//alert(tabVolumes[0]);
tabVolumes[1] = calculateVolume2(TailFillet);
} else { tabVolumes[1] = 0; }
if (height != 0) {
tabVolumes[2] = calculateVolume2(degraissageFillet);
} else { tabVolumes[2] = 0; }
var ind = 3;
var HeadFilletMesh = new THREE.Mesh(HeadFillet, new THREE.MeshBasicMaterial({ map: texture }));
var TailFilletMesh = new THREE.Mesh(TailFillet, new THREE.MeshBasicMaterial({ map: texture }));
var degraissageFilletMesh = new THREE.Mesh(degraissageFillet, new THREE.MeshBasicMaterial({ map: texture }));
HeadFilletMesh.position.set(0, 0, 20);
degraissageFilletMesh.position.set(-20, 0, 0);
TailFilletMesh.position.set(0, 0, -20);
scene.add(HeadFilletMesh);
scene.add(TailFilletMesh);
scene.add(degraissageFilletMesh);
//scene.add(newFilletMesh);
var cloneHeadFilletMesh = HeadFilletMesh.clone();
var cloneTailFilletMesh = TailFilletMesh.clone();
var clonedegraissageFilletMesh = degraissageFilletMesh.clone();
var mesh_decoupe = new THREE.Object3D;
mesh_decoupe.add(cloneHeadFilletMesh);
mesh_decoupe.add(cloneTailFilletMesh);
mesh_decoupe.add(clonedegraissageFilletMesh);
if (width != 0) {
var paveGeom = new THREE.BoxGeometry(300, 300, width);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
var fillet2BSP = new ThreeBSP(newFilletMesh);
var intersectionPave = new THREE.Geometry();
intersectionPave = fillet2BSP.intersect(paveBSP);
var geometryPave = new THREE.Geometry();
geometryPave = intersectionPave.toGeometry();
var newMesh = new THREE.Mesh(geometryPave, new THREE.MeshBasicMaterial({ map: texture }));
//alert(geometryPave.faces.length);
while (geometryPave.faces.length != 0) {
var z = paveMesh.position.z + width + 5;
paveMesh.position.set(0, 0, z);
paveBSP = new ThreeBSP(paveMesh);
//scene.add(paveMesh);
fillet2BSP = new ThreeBSP(newFilletMesh);
intersectionPave = filletBSP.intersect(paveBSP);
geometryPave = intersectionPave.toGeometry();
tabVolumes[ind] = calculateVolume2(geometryPave);
ind = ind + 1;
var newMesh = new THREE.Mesh(geometryPave, new THREE.MeshBasicMaterial({ map: texture }));
newMesh.position.set(0, 0, newMesh.position.z);
scene.add(newMesh);
var meshSave = newMesh.clone();
mesh_decoupe.add(meshSave);
}
document.body.style.cursor = '';
} else {
scene.add(newFilletMesh);
document.body.style.cursor = '';
tabVolumes[3] = 0;
tabVolumes[4] = calculateVolume2(newFilet);
}
// }
//}
//else {
// scene.add(newFilletMesh);
// tabVolumes[ind] = calculateVolume2(newFilet);
//}
//alert(calculateVolume2(newBSP.toGeometry()));
//afficher les volumes dans la textarea
var txtVolume = document.getElementById("txtVolume");
txtVolume.value = tabVolumes.join("\n");
//var exporter = new THREE.OBJExporter();
//var result = exporter.parse(mesh_decoupe);
//var blob = new Blob([result], { type: 'text/plain' });
//saveAs(blob, 'dechets.obj');
}
});
//scene.add(object);
}, onProgress, onError);
renderer = new THREE.WebGLRenderer();
renderer.setSize(800, 500, false);
document.getElementById('canvas3D').innerHTML = "";
document.getElementById('canvas3D').appendChild(renderer.domElement);
}
function animate() {
requestAnimationFrame(animate);
camin();
renderer.render(scene, camera);
}
function camin() {
camera.position.y -= .1;
}
function volumeOfT(p1, p2, p3) {
var v321 = p3.x * p2.y * p1.z;
var v231 = p2.x * p3.y * p1.z;
var v312 = p3.x * p1.y * p2.z;
var v132 = p1.x * p3.y * p2.z;
var v213 = p2.x * p1.y * p3.z;
var v123 = p1.x * p2.y * p3.z;
return (-v321 + v231 + v312 - v132 - v213 + v123) / 6.0;
}
function calculateVolume2(object) {
var volumes = 0.0;
for (var i = 0; i < object.faces.length; i++) {
var Pi = object.faces[i].a;
var Qi = object.faces[i].b;
var Ri = object.faces[i].c;
//alert (Pi);
var P = new THREE.Vector3(object.vertices[Pi].x, object.vertices[Pi].y, object.vertices[Pi].z);
//alert(object.vertices[Pi].x);
var Q = new THREE.Vector3(object.vertices[Qi].x, object.vertices[Qi].y, object.vertices[Qi].z);
var R = new THREE.Vector3(object.vertices[Ri].x, object.vertices[Ri].y, object.vertices[Ri].z);
volumes += volumeOfT(P, Q, R);
}
return Math.abs(volumes);
}
}

Set/get name of an image take from canvas

Hi nobody know how to get or maybe set the name of an image in a canvas?
i use this code to save a canvas as image, but i don't know how get the name of the image or how set .
My goal is to load a image or pdf, draw on it and save in another image or pdf.
var img = new Image();
var startimg="img/green.jpg";
$scope.image=startimg;
img.src = startimg;
var sourceCanvas = document.getElementById('signatureCanvas');
var context = sourceCanvas.getContext('2d');
var canvasFirma = document.getElementById('tempCanvas');
var contextFirma = canvasFirma.getContext('2d');
img.onload = function() {
sourceCanvas.width = img.width;
sourceCanvas.height = img.height;
//context.drawImage(img, 0, 0);
console.log('The canvas size is '+ sourceCanvas.width +'*'+ sourceCanvas.height);
console.log('The image size is '+ img.width +'*'+ img.height);
context.drawImage(img, 0, 0, img.width, img.height);
}
var signaturePad = new SignaturePad(canvasFirma);
$scope.clearCanvas = function() {
signaturePad.clear();
}
$scope.saveCanvas = function() {
$scope.clearSave = false;
$scope.FirmaBtn = true;
$scope.canvasSi = false;
//salvo la firma
var firma = signaturePad.toDataURL("image/jpeg");
$timeout( function(){
$scope.signature = firma;
if ($scope.signature) {
$scope.resizeCanvas();
}
}, 200);
};
//to merge canvas and image
var canvasF = document.getElementById("canvasFinale");
var ctx = canvasF.getContext("2d");
var img1 = loadImage('img/green.jpg', main);
/*this one "image.jpg" i need to get the name or give new one because this is for example*/
var img2 = loadImage('img/image.jpg', main);
var imagesLoaded = 0;
function main() {
imagesLoaded += 1;
if(imagesLoaded == 2) {
// composite now
ctx.drawImage(img1, 0, 0);
//questo da la transparenza magari toglierlo
ctx.globalAlpha = 0.5;
ctx.drawImage(img2, 0, 0);
}
}
function loadImage(src, onload) {
var img = new Image();
img.onload = onload;
img.src = src;
/*
canvasF.width = img.width;
canvasF.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
*/
console.log("src "+ src);
return img;
}
$timeout( function(){
$scope.signature = firma;
if ($scope.signature) {
$scope.resizeCanvas();
}
}, 200);
};
$scope.resizeCanvas = function () {
canvasFirma.width = canvasFirma.offsetWidth * ratio;
canvasFirma.height = canvasFirma.offsetHeight * ratio;
canvasFirma.getContext('2d').scale(ratio, ratio);
console.log("resize canvasFirma 2");
};
You can download the canvas image with a custom name by making use of the download attribute.
Codepen Example
var canvas = $("#canvas")[0];
var ctx = canvas.getContext('2d');
ctx.fillRect(10,10,10,10);
$("#download").on("click", function(e) {
$("#download").attr("download", "CustomName.png");
$("#download").attr("href", canvas.toDataURL().replace(/^data:image\/[^;]/, 'data:application/octet-stream'));
});

Resources